cmp
cmp

Reputation: 452

Split each letter in a div into its own span

I have a div that has a heading tag.

<div class="hero__title">
   <h1 class="hero__title-txt">Page title</h1>
</div>

I'm trying to get the desired output

<div class="hero__title">
   <h1 class="hero__title-txt">
       <span>P</span>
       <span>a</span>
       <span>g</span>
       <span>e</span>
       <span>T</span>
       <span>i</span>
       <span>t</span>
       <span>l</span>
       <span>e</span>
   </h1>
</div>

This is in order to use some CSS to style a cool in animation. I will worry about the Javascript to separate words another time.

span{
     transition: 1s left ease;
}
span:nth-child(1){
     transition-delay: 400ms;
}
span:nth-child(2){
     transition-delay: 600ms;
}
span.word{
     display:inline-block;
     margin-right:10px;
}

This nice SO article was a good guide but as pointed out in one of the responses, it will only work if the last span is emitted. There are tons of jQuery options, yes, but in my first project without jQuery, I'd love to do this with native script.

<div id="text">Hello, <span class="name">John</span></div>

var text = document.getElementById("text");
var msg = text.textContent;
var name = document.getElementsByClassName("name")[0].textContent;

// remove name from msg
msg = msg.substring(0,msg.length - name.length);
// to char array
msg = msg.split('');
name = name.split('');

text.innerHTML = "<span>" + msg.join("</span><span>") + "</span>";
text.innerHTML += "<span class=\"name\">" + name.join("</span><span class=\"name\">") + "</span>";

Upvotes: 0

Views: 1612

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

This is much simpler than what you're doing. See comments inline.

let h1 = document.querySelector(".hero__title-txt"); // Get reference to the h1
let text = h1.textContent.split("");                 // Get the text content into an array

let result = ""; // Will hold output

// Loop over the array
text.forEach(function(char){
  // Append a new span only if the current char is not a space
  result += (char.trim() === "") ? "" : "<span>" + char + "</span>";
});

h1.innerHTML = result;  // Reset the h1's content

console.log(h1.outerHTML); // Test
<div class="hero__title">
   <h1 class="hero__title-txt">Page title</h1>
</div>

Upvotes: 4

Related Questions