Add/Remove Classes on the Fly with jQuery
jQuery provides methods that allow you to add and remove classes that are contained in your style sheet. Here's an overview.
The jQuery addClass()
, removeClass()
, and toggleClass()
methods enable you to dynamically add and remove classes on HTML elements. This can be useful when applying multiple style declarations, and it allows you to keep your styles within your style sheet while using jQuery to access them.
The addClass()
Method
Here's how to use the addClass()
method:
And here it is in action:
You can also provide multiple classes separated by a space, like this:
The removeClass()
Method
The removeClass()
enables you to remove a single class, multiple classes, or all classes from each element in the set of matched elements.
Like this:
Working example:
Multiple class names can be provided, separated by a space.
The toggleClass()
Method
The toggleClass()
method combines the functionality of addClass()
and removeClass()
to produce a "toggle" effect where the class is added or removed, depending on whether the class is already attached to the element or not.
For example, a user clicks an element which adds a class to it. When the user clicks again, the class is removed. When they click again, it's added back, and so on.
Here's how to use the toggleClass()
method:
And here it is in action. Click the elements multiple times to get the toggle effect:
As with the other methods, multiple class names can be provided, separated by a space.