...

How can I remove a specific class from all elements?

How to remove this class from page elements?

Example:

<div class="fan light"> ... </div>
<div class="light"> ... </div>
<h3 class="seahorse light"> SomeHeading </h3>

      

I want to remove the class light

from all elements of the page!

How can I do this using jquery or javascript?

+4


source to share


3 answers


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

      

+31


source


Use jQuery

to find all items DOM

with class

light

and remove class

.



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

      

+3


source


Short simple JavaScript:

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

      

0


source







All Articles