How can I remove a specific class from all elements?
Just find all the elements that have a 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, "");
(This depends on the browser supporting .getElementsByClassName()
.) Note that the loop looks a little odd, always working on item 0 of the list of items. This is because the lists returned from the API, for example .getElementsByClassName()
, are live - they change to reflect changes in the DOM. When a class is removed from an element, it is no longer in the list of elements with that class name. So by removing the class from the first item in the list, that item will disappear. Eventually the list will be empty. (I always thought this was bizarre behavior that grossly violates the principle of least surprise, but there you go.)
Finally, a comment noted that newer browsers (IE10 +) support a DOM element property called .classList
. This is a list of class names, plus it supports some convenience methods. In particular:
var lights = document.getElementsByClassName("light");
while (lights.length)
lights[0].classList.remove("light");
source to share