What I currently have in my JS file:
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.
className
returns a string with all of the classes on the element. You need to see if that string contains your class:
if (documentElement.className.indexOf("child") != -1){
Use indexOf
Regarding what @Roberrrt said - you can achieve this simply selecting the 'child class' and applying a style to it.
For a visual example.
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. 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"
:
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 )
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.