How do I remove a given class from the page elements?
Example:
<div class="fan light"> ... </div>
<div class="light"> ... </div>
<h3 class="seahorse light"> SomeHeading </h3>
I want to drop the class light
from all elements of the page!
How do I do that using jquery or javascript?
The syntax for Removing CSS classes to an element:removeClass(class_name);
The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected 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');
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