Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 424
Reza Saberi Avatar asked Oct 14 '14 13:10

Reza Saberi


People also ask

How do you remove a class in CSS?

The syntax for Removing CSS classes to an element:removeClass(class_name);

How do I delete a class?

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.


2 Answers

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");
like image 100
Pointy Avatar answered Oct 21 '22 17:10

Pointy


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

$('.light').removeClass('light');
like image 25
Alex Avatar answered Oct 21 '22 17:10

Alex