Remove and add class using jquery

July 12, 2020
Jquery

There are many cases where you want to either add the class or remove it dynamically via jquery.
For this purpose we have addClass() , removeClass() and toggleClass(),

In the tutorial, we will cover each of these in brief.

Are you ready ? Lets start 💻 !

Jquery addClass()

Jquery addclass() is used to add one or multiple classes dynamically to the selected element.

Here is the small example of code in which element with id box having class bg added dynamically

//adding the bg class to the box id element
$('#box').addClass('bg');
Note:When you are adding/removing or toggling the class, you dont have to add the will not have dot(.) to it.

Here is the example of adding multiple classes. In this example we are adding bg class, red class and orange class

//adding the bg class, red class and orange class
$('#box').addClass('bg red orange');


Jquery removeClass()

Just like the addclass() we have removeClass() to remove the class or classes.

Here is the small example of code in which element with id box having class bg removed dynamically

//removing the bg class from the box id element
$('#box').removeClass('bg');

Same as this, we can remove the multiple classes

//removing the bg class, red class and orange class
$('#box').removeClass('bg red orange');

Jquery toggleClass()

Method 1:

First method which we can use to toggleclass is using addclass() and removeclass() in one line

Here is the example of first removing the bg class and adding the orange class

//removing the bg class and adding the orange class
$('#box').removeClass('bg').addClass('orange');

Here is the another example of first adding the bg class and then removing the orange class

//adding the bg class and then remove the orange class
$('#box').addClass('bg').removeClass('orange');

Method 2:

Another method is using toggleClass(). toggleClass() works in a way that if the class is not added it will add the class otherwise it will remove the class.

Here is the example with explaining

// Case 1: If bg class was already applied to the box id element, then by using this next line it will remove the bg class.
// Case 2: If bg class was not applied before the box id element, then by using this next line it will add the bg class
$('#box').toggleClass('bg');

Same as the addClass() and removeClass(), in toggleClass() can also have multiple classes

//bg will be added if it was not added before, otherwise it will remove it
//orange will be added if it was not added before, otherwise it will remove it
//red will be added if it was not added before, otherwise it will remove it
$('#box').toggleClass('bg orange red');

Conclusion

Hope you learned today how to add and remove single/multiple class dynamically jquery. Hope you like it. Let me know in comments if you have any questions and i will try to answer all of them

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon