简体   繁体   English

使用JavaScript更改HTML中的文本背景颜色

[英]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. 我已经使用CSS属性background-color了。 But it is changing the color of the whole list item. 但这改变了整个列表项的颜色。 i have to change the background color only by using javascript. 我只需要使用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. 通过将font标签嵌入到javascript中无法实现的文本中。 I have done this with the help of Inspect Element feature of Google Chrome 我是借助Google Chrome浏览器的“ 检查元素”功能完成此操作的

Your js example is not valid and should not do anything ... 您的js示例无效,不应执行任何操作...

You need to set the style on each span element; 您需要在每个span元素上设置样式;

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. 如上所述-您的JS无效。 For starters, the function name is 'getElementsByClassName' rather than 'getElementByClaassName'. 对于初学者,函数名称为“ getElementsByClassName”,而不是“ 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. jQuery将为您提供一个如Sameera概述的不错的快捷方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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