How to remove a specific class from all elements?
Just find all the elements that do have the class, and remove it:
$(".light").removeClass("light");
With plain JavaScript:
var lights = document.getElementsByClassName("light");
while (lights.length)
lights[0].className = lights[0].className.replace(/\blight\b/g, "");
(That relies on the browser supporting .getElementsByClassName()
.) Note that the loop looks a little weird, always operating on element 0 of the element list. That's because the lists returned from APIs like .getElementsByClassName()
are live — they change to reflect changes in the DOM. When a class is removed from an element, it's no longer in the list of elements with that class name. Thus by removing the class from the first element in the list, that element goes away. Eventually the list will be empty. (I've always thought that this was a bizarre behavior that flagrantly violates the principle of least surprise, but there you go.)
Finally it's pointed out in a comment that newer browsers (IE10+) support a DOM element property called .classList
. It's a list of class names, plus it supports some handy methods. In particular:
var lights = document.getElementsByClassName("light");
while (lights.length)
lights[0].classList.remove("light");
Use jQuery
to find all DOM
elements with the class
light
and remove the class
.
$('.light').removeClass('light');