Remove and add class using Jquery

Learn how to effectively remove and add class using Jquery.

DOM elements can have multiple classes which can be used for different purposes according to the need.

Add class in Jquery

Jquery has method called addClass() which can be used to add one or more class to the DOM elements.

It takes class names in the string format.

//Add red class to the 
//element with id abc
$("#abc").addClass('red');

To add multiple classes pass them space separated in string format.

//Add multiple class to the 
//element with id abc
$("#abc").addClass('red yellow pink blue');

addClass() method assigns the given list of classes to all the selected element.

//Add multiple class to the 
//element with input type text
$("input[type='text']").addClass('red yellow pink blue');

If the class is already present then it will overwrite it.


Remove class using Jquery

Jquery has method called removeClass() which can be used to remove one or more class from the DOM elements.

//Remove red class from the 
//element with id abc
$("#abc").removeClass('red');

To remove multiple classes pass the list of class space separated.

//Remove red class from the 
//element with class xyz
$(".abc").removeClass('red yellow pink');

removeClass() method removes the given list of classes from all the selected element.

//Remove multiple class to the 
//element with input type text
$("input[type='text']").removeClass('red yellow pink blue');

If the class is not present then it will simply ignore it.


Toggle class in Jquery

We can use removeClass and addClass together to toggle the classes.

//Toggle class to the 
//element with id abc
$("#abc").removeClass('red yellow').addClass('red yellow');

This will remove the 'red yellow' class and add it again.

Jquery also has another function called toggleClass() which can be used for toggling classes.

//Toggle class to the 
//element with id abc
$("#abc").toggleClass('red yellow');

If the class is present then it will remove them else it will add them.

Beware while using this method because it may some time result in weird behavior.

$('.red').toggleClass('red yellow');

In this case it will remove the 'red' because it is already present and add the 'yellow'. So once the 'red' is removed your selector will not work $('.red').