What I’m trying to do is to get the elements with the class name no-js
and replace it with js
.
I have no idea how to do this. I tried Googling around but couldn’t find anything, so does anyone know how to do this?
My goal is to have a menu show a drop-down navigation when clicked, but if JavaScript is disabled I want it to show on hover with CSS (I’ve already done that).
I’ve put my code on JSFiddle.
classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list. Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.
Element Class Names Another way to alter the style of an element is by changing its class attribute. class is a reserved word in JavaScript, so in order to access the element's class, you use element. className .
You need to iterate the returned elements and replace that portion of the class name on each one:
var els = [].slice.apply(document.getElementsByClassName("no-js"));
for (var i = 0; i < els.length; i++) {
els[i].className = els[i].className.replace(/ *\bno-js\b/g, "js");
}
Note that getElementsByClassName
returns a "live list", which is why it's necessary to first make a copy of the return value (using [].slice
) and iterate that list instead).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With