Home » Jquery » Removing multiple classes (jQuery)

Removing multiple classes (jQuery)

Posted by: admin November 2, 2017 Leave a comment

Questions:

Is there any better way to rewrite this:

$('element').removeClass('class1').removeClass('class2');

Can’t use removeClass(); as it would remove ALL classes, which I don’t want.

Thanks

Answers:
$("element").removeClass("class1 class2");

From removeClass(), the class parameter:

One or more CSS classes to remove from
the elements, these are separated by
spaces.

Questions:
Answers:

$('element').removeClass('class1 class2');

Here are the docs.

Questions:
Answers:

http://docs.jquery.com/Attributes/removeClass

One or more CSS classes to remove from the elements, these are separated by spaces.

Questions:
Answers:

The documentation says:

class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.

Example:

Remove the class ‘blue’ and ‘under’ from the matched elements.

$("p:odd").removeClass("blue under");
Questions:
Answers:

There are many ways can do that!

jQuery

  1. remove all class
    $("element").removeClass();
    OR
    $("#item").removeAttr('class');
    OR
    $("#item").attr('class', '');
    OR
    $('#item')[0].className = '';

  2. remove multi class
    $("element").removeClass("class1 ... classn");
    OR
    $("element").removeClass("class1").removeClass("...").removeClass("classn");

Native Javascript

  1. remove all class
// remove all items all class  
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
    items[i].className = '';
}
  1. remove multi class
// only remove all class of first item
const item1 = document.querySelector('item');
item1.className = '';