Avoid extra use of the span
My question is that I have html code <p> Hello World </p>
And I want to change the css of each letter using JavaScript. Basically, I changed the background color to make the animation. Is there a way to do this without making a gap or some kind of tag around each letter and going through all this struggle?
I have a string array with colors and a method to call the correct color (data index attribute).
Thank!
EDIT: I have a word changing color and thought of the idea by creating a function that iterates over the innerHTML string indices and assigns the data index to the space of the letter by editing the Cymen function below . Is this a good approach?
source to share
You will need to use a JavaScript function to wrap each character in a <span>
.
window.onload = function() { // when everything loads, run the function
var elem = document.getElementById( "someId" );
var text = elem.innerHTML; // get the <p> text content
elem.innerHTML = ""; // then make the <p> empty
for( var i=0; i<text.length; i++ ) { // for each character in the text
elem.innerHTML += "<span>"+text[i]+"</span>";
}
};
Don't forget to change "someId" to your element's id <p>
.
You can access every single character inside the loop for
with text[i]
.
source to share
It will take quite a bit of code to fully outline it, but if it is very important in your case not to add some type of wrapping element, then I believe it is possible with a dynamically generated background image.
Approximately the following steps:
- Create
Range
with start and end around each symbol in the.textContent
item you care about. -
.getBoundingClientRect()
on each range to get the displayed dimensions. - Draw rectangles of the desired color on
<canvas>
. - Export
<canvas>
as URIdata
. - Use URI
data
likebackground-image
. - Repeat for each item displayed in the block you want.
Keep in mind that there will undoubtedly be different edge cases in this approach and the possible limitations of browser support. Obviously, just wrapping each character is much easier.
source to share