'How can I change the color of one letter in JavaScript?

I have a string and I want to change just one color letter in JavaScript.

HTML:

<div id="lettersList">Hello</div>

In my JavaScript file, I retrieve like this (normal)

var lettres = document.getElementById("lettersList");

But I don't know how to change the color of just one word (the 'o' of "hello" for example). If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.



Solution 1:[1]

You can use the replace() method on the innerHTML property of the element:

const element = document.querySelector('#lettersList');
element.innerHTML = element.innerHTML.replace('o', '<span style="color: red;">o</span>');
<div id="lettersList">Hello</div>

Solution 2:[2]

In your code :

 var letters = document.getElementById()

you actually retrieve the whole element, not the text in it. That might be the reason that it changed its color totally.

So I suggest you to use

document.getElementById().innerHtml()

. This function will retrieve the content in your HTML tags (div). Then you do the color changing like

for(var i = 0; i<letters.length; i++){
    //only change the one you want to
    if(i == 4 // or whatever you like){
        element.innerHTML = element.innerHTML.replace(letters[i], '<span style="color: yellow;">'+letters[i]+'</span>');
    }
}

Solution 3:[3]

it works with

for(var i = 0; i<letters.length; i++){ if(i == 4 { element.innerHTML =element.innerHTML.replace(letters[i], '<span style="color:yellow;">'+letters[i]+'</span>');}}

But if a word contains two similar letters, I can't color the both... Why that ?

Solution 4:[4]

if a word contains two similar letters then with the for loop we can use position of letter as i inside if i == n , replace(letter[n], styled span tag)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nisse Engström
Solution 3 SarahB
Solution 4 Nava