deviloper
deviloper

Reputation: 7240

How to remove a specific class from all elements?

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?

Upvotes: 21

Views: 43378

Answers (3)

Vasin Yuriy
Vasin Yuriy

Reputation: 535

Short plain JavaScript:

[].forEach.call(document.querySelectorAll('light'), function (el) {
    el.classList.remove('hidden');
});

Upvotes: 4

Pointy
Pointy

Reputation: 413702

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");

Upvotes: 70

Alex
Alex

Reputation: 35399

Use jQuery to find all DOM elements with the class light and remove the class.

$('.light').removeClass('light');

Upvotes: 4

Related Questions