Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding style color on the first letter of each word in Javascript is not working

I’m trying to add color on first letter of each word in a dynamic html element. But the style is not working in my Javascript code.

here is my code: https://jsfiddle.net/Devbuddy/1q9wcmbu/5/

<h1 id="heading">
The heading text here
</h1>

    window.onload = (event) => {
    const headingTxt = document.getElementById('heading').innerText;
    const headingM = headingTxt.match(/\b(\w)/g);
    const headingTxtJ = headingM.join('');

    for(let i=0; i < headingTxtJ.length; i++){
        headingTxtJ[i].style.color = 'red';
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use JS to wrap your first letters in a span and apply style to them.

window.onload = (event) => {
  const heading = document.getElementById('heading');
  const headingTxt = heading.innerText;
  const headingWords = headingTxt.split(/[ \t]+/); //regex matches any number of spaces
  heading.innerHTML = headingWords.map(word => {
      const firstLetter = word.substring(0,1);
      const restOfWord = word.substring(1,word.length);
      return `<span style="color: red">${firstLetter}</span>${restOfWord}`
  }).join(' ');

}
<h1 id="heading">
  The heading    text    here
</h1>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading