▷ Separate a Text into Individual HTML Tags with JavaScript

When working with HTML texts, we sometimes need to manipulate their structure more granularly, such as splitting a title or paragraph into individual HTML tags. This can be useful for animated effects or user interaction. Below, I will explain how you can separate a text into words and characters, encapsulating them in tags <div> and <span> using JavaScript.

The Code

GitHub repository: Full code

The following JavaScript code separates a title from a web page, word by word and then, character by character. Each word is wrapped in a container <div>, and each character within the word is wrapped in a <span>. This allows for a more precise and stylized manipulation of the text.

// Wait for the DOM content to be fully loaded
document.addEventListener("DOMContentLoaded", function () {
  // Select the element that contains the section title
  const textContainer = document.querySelector("#sectionTitle");

  // Gets the content of the title
  const textToSeparate = sectionTitle.innerHTML;

  // Split the title into words using a space as a separator
  textContainer.innerHTML = textToSeparate
    .split(" ")
    .map((e) => {
      // Create a div container for each word
      const wordContainer = document.createElement("div");
      wordContainer.classList.add("word-container");

      // Split the word into individual characters
      const word = e.split("").map((e) => {
        // Create a span element for each character
        const character = document.createElement("span");
        character.classList.add("character");
        character.innerHTML = e;

        // Returns the HTML code of the character
        return character.outerHTML.toString();
      });

      // Fills the word container with the characters
      wordContainer.innerHTML = word.join("");

      // Returns the HTML code of the word container
      return wordContainer.outerHTML.toString();
    })
    // Combines all the fragmented words to reconstruct the title
    .join(" ");
});

Step by Step Explanation

  1. Listen for the DOMContentLoaded Event
    The script starts by listening for the DOMContentLoaded event to ensure that the DOM is fully loaded before executing the code.
  2. Select the Text Container
    We use document.querySelector to select the element that contains the text, in this case, an element with the ID #sectionTitle. This can be any other HTML element, such as a header or a paragraph.
  3. Get the Text Content
    We use textContainer.innerHTML to get the current content of the selected element.
  4. Split the Text into Words
    The method split(" ") splits the text into an array of words, using spaces as delimiters.
  5. Create a Container for Each Word
    For each word in the array, we create a new element <div> with the class word-container, which will contain the characters of that word.
  6. Split Words into Characters
    For each word, the function split("") splits the word into individual characters, and then each character is wrapped in a <span> with the class character.
  7. Rebuild the Text
    After creating the containers for each word and character, we combine them back into a single block of HTML with join(" "), which joins the words separated by spaces.

Practical Applications

  • Text Animations: You can apply CSS transitions to animate the appearance or movement of each character or word individually.
  • Individual Styles: It is possible to apply different styles to each letter or word, making it easier to create dynamic and creative typographic designs.
  • User Interactions: You can add events to each character or word, such as a "hover" effect or a click to enhance interactivity.

Conclusion

This approach of separating text into individual HTML tags with JavaScript is a powerful technique for those looking to customize the presentation of web content at a detailed level. By using the tags <div> and <span>, a structure is achieved that is easily accessible and manipulable with both CSS and JavaScript, opening up a range of possibilities for animations, interactions, and design.

GitHub repository: Complete code

0/Leave a comment/Comments

Hello! We're so glad you've made it this far and are reading this article on Edeptec.

This form is an open space for you: you can leave a comment with your questions, suggestions, experiences, or simply your opinion on the topic discussed.

» Did you find the information helpful?
» Do you have any personal experiences you'd like to share?
» Do you have any topics you'd like to see covered in future articles?

Remember that this space is for learning and sharing, so we encourage you to participate respectfully and constructively. Your comments can help other readers who are on the same path, whether in electronics, programming, sports, or technology.

Thank you for being part of this learning community! Your participation is what makes this project grow.