Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the `no-js` class name by `js` on all elements? [duplicate]

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.

like image 568
user1064634 Avatar asked Jan 03 '12 06:01

user1064634


People also ask

What is the use of classList in JavaScript?

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.

How can the style class of an element be changed?

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 .


1 Answers

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).

like image 164
Wayne Avatar answered Oct 22 '22 09:10

Wayne