[英]If a class contains a certain name, change the style of that element
What I currently have in my JS file: 我当前在JS文件中拥有什么:
if (documentElement.className("child") != -1){
documentElement.className("child").backgroundColor="red";
}
Basically as the title implies, I want all the classes with the name "child" on the page to change their background color to red. 基本上如标题所示,我希望页面上所有名称为“ child”的类将其背景颜色更改为红色。
className
returns a string with all of the classes on the element. className
返回一个包含元素上所有类的字符串。 You need to see if that string contains your class: 您需要查看该字符串是否包含您的类:
if (documentElement.className.indexOf("child") != -1){
Use indexOf
使用indexOf
Regarding what @Roberrrt said - you can achieve this simply selecting the 'child class' and applying a style to it. 关于@Roberrrt所说的-您只需选择“子类”并为其应用样式即可实现此目的。
For a visual example. 作为一个直观的例子。
http://codepen.io/anon/pen/GNMJjr http://codepen.io/anon/pen/GNMJjr
In your code: 在您的代码中:
documentElement.className("child").backgroundColor="red";
That wouldn't work, this is a better way of achieving what you want: 那是行不通的,这是实现您想要的更好的方法:
document.querySelector('.child').style.backgroundColor = "red";
I still recommend using CSS. 我仍然建议使用CSS。 This is redundant and extremely verbose. 这是多余的,而且非常冗长。
Try this maybe (tested on about:blank page with 5 <div>
with 2 of them with the class="red"
: 也许尝试一下(在about:blank页面上用5 <div>
进行测试,其中2个使用class="red"
:
var red = [];
red = document.querySelectorAll(".red");
for (var i = 0; i < red.length; i += 1) {
red[i].style.backgroundColor = "red";
}
If you really want to verify if the class name contains a string, use classList.contains
(it often have resolved this kind of problem for me, check the MDN page ) 如果您确实要验证类名是否包含字符串,请使用classList.contains
(它通常已经为我解决了此类问题,请查看MDN页面 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.