admin管理员组

文章数量:1278787

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.

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.

Share Improve this question edited Jun 4, 2017 at 15:55 Michał Perłakowski 92.7k30 gold badges163 silver badges187 bronze badges asked Jun 4, 2017 at 15:49 SarahBSarahB 1551 silver badge11 bronze badges 3
  • 2 it changes all the text(of course) are you sure ???? – Pranav C Balan Commented Jun 4, 2017 at 15:51
  • yes, i'm sure ;) – SarahB Commented Jun 4, 2017 at 15:57
  • 1 lettres.length and lettres[i] would be undefined :) – Pranav C Balan Commented Jun 4, 2017 at 16:02
Add a ment  | 

4 Answers 4

Reset to default 10

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>

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

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 ?

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)

本文标签: htmlHow can I change the color of one letter in JavaScriptStack Overflow