jQuery toggleClass() method
Example
Toggle the addition and removal of the
"main" class on all elements:
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
p
"
)
.
toggleClass
(
"
main
"
)
;
}
)
;
Try it »
Definition and Usage
The toggleClass() method toggles adding and removing one or more classes on the selected elements.
This method checks the specified class on each element. If it is not present, the class is added; if it is already set, it is removed. This is known as a toggle effect.
However, by using the "switch" parameter, you can specify to only remove or only add the class.
Syntax
$(
selector
).toggleClass(
classname,
function
(index,currentclass),switch
)
| Parameters | Description |
|---|---|
| classname | Required. Specifies one or more class names to add or remove. To specify several classes, separate the class names with spaces. |
| function*(index,currentclass)* | Optional. Specifies a function that returns one or more class names to add/remove.
|
More examples
Toggling the addition and removal of classes
How to use the toggleClass() method to toggle the addition and removal of classes.
Toggling classes using a function
Use a function to specify which class name the current element should toggle.
Using the switch parameter
How to use the switch parameter to only add or remove class names.
jQuery HTML/CSS methods