0

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';
    }
}
Devbuddy
  • 231
  • 4
  • 15

4 Answers4

2

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>
WillD
  • 5,170
  • 6
  • 27
  • 56
1

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>
GrafiCode
  • 3,307
  • 3
  • 26
  • 31
1

You can use regex replace to do this. Simplified and cleaner.

let str = document.getElementById("heading");
str.innerHTML = str.innerHTML.replace(/\b(\w)/g, "<span class='first-letter'>$1</span>")
.first-letter {
  color: red;
}
<h1 id="heading">
  The heading text here
</h1>
JStanton
  • 425
  • 5
  • 12
0
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')
Denis Rudov
  • 833
  • 8
  • 16