ExampleToggle between adding and removing the "main" class for p elements:
Try it yourself » |
The toggleClass() method toggles between adding and removing one or more classes for the selected elements.
This method checks each element for the specified classes. The classes are added if missing, and removed if already set - This creates a toggle effect.
However, by using the "switch" parameter, you can specify to only remove, or only add a class.
$(selector).toggleClass(class,switch) |
Parameter | Description |
---|---|
class | Required. Specifies one or more class names to add or remove. To specify several classes, separate the class names with a space. |
switch | Optional. A Boolean value specifying if the class should be added (true), or removed (false). |
Using a function to specify which classes should be toggled for the selected elements.
|
Try it yourself » |
Parameter | Description |
---|---|
function(index,class) | Specifies a function that returns one or more class names to add/remove.
|
switch | Optional. A Boolean value specifying if the class should be added (true), or removed (false). |
![]() |
Try it Yourself - Examples |
Toggle between adding and removing a class
How to use the toggleClass() method to toggle between adding and removing a
class.
Using the switch parameter
How to use the switch parameter to only add or remove a class.