简体   繁体   中英

Change Text BackGround Color in HTML using JavaScript

<ul>
    <li>
        <span class="name">Tortilla de blé</span>
    </li>
</ul>

This is the original source. I need to change the background Color of just the text in the tag. I have used css property background-color for it. But it is changing the color of the whole list item. i have to change the background color only by using javascript.

var ea = document.getElementsByClassName('name');
for(var i = 0; i < ea.length; i++)
    ea[i].style.backgroundColor = "yellow";

(Changed the Older Script as that was not correct, mistakenly written)

My Result:

原始图片

Expected Result: What could i do to just highlight the text in the tag and not the whole tag.

预期图像

I have produced the expected result by editing the source code like below:

<ul>
    <li>
        <span class="name"><font style="bakground-color:yellow">Tortilla de blé</font></span>
    </li>
</ul>

By Embedding font tag to the text which is not possible with the javascript. I have done this with the help of Inspect Element feature of Google Chrome

Your js example is not valid and should not do anything ...

You need to set the style on each span element;

var ea = document.getElementsByClassName('name');
for(var i = 0; i < ea.length; i++)
        ea[i].style.backgroundColor = "yellow";

As explained above - your JS is not valid. For starters, the function name is 'getElementsByClassName' rather than 'getElementByClaassName'.

You then need to have it loop through the elements and set their properties individually. JQuery will give you a nice shortcut as outlined by Sameera.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM