how to replace class HTML name with javascript

user1064634 picture user1064634 · Jan 3, 2012 · Viewed 48.8k times · Source

ok so what I'm trying to do is to get the element's with the class name 'no-js' and replace it with 'js', so I have NO idea how to do this, I tried google around But couldn't find anything, so does anyone now how to do this?

what I'm trying to make Is this menu that when you click on a Plus button it has this drop down menu, 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, heres the link: http://jsfiddle.net/MrPumpkin22/v9dcC/10/

thanks.

Answer

Wayne picture Wayne · Jan 3, 2012

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