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

Time:08-27

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';
    }
}

CodePudding user response:

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>

CodePudding user response:

You can split() your heading text into words, then use substr() on each word to extract the first letter and apply styles to it.

const headingTxt = document.getElementById('heading');

const words = headingTxt.innerText.split(' ')

let output = ''

for (let word of words) {
  output  = '<span style="color:red;">'   word.substr(0, 1)   '</span>'   word.substr(1, word.length)   ' '
}

headingTxt.innerHTML = output
<h1 id="heading">The heading text here</h1>

CodePudding user response:

const colorizeLettersHtml = (str = '', color = '#ccc') => str.split(/  /)
   .map((word) => {
         const [first, ...others] = word
         return `<span style="color:${color}">${first}</span>${others.join('')}`
    })
   .join(' ')

and with real DOM element

const elementWithText = document.querySelector('#heading')
 elementWithText.innerHTML = 
      colorizeLettersHtml(elementWithText.textContent, '#f60')
  • Related