Example

Toggle between adding and removing the "main" class for p elements:

$("button").click(function(){
  $("p").toggleClass("main");
});

Try it yourself »

Definition and Usage

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.


Syntax

$(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).


Toggle Classes Using a Function

Using a function to specify which classes should be toggled for the selected elements.

Syntax

$(selector).toggleClass(function(index,class),switch)
Try it yourself »

Parameter Description
function(index,class) Specifies a function that returns one or more class names to add/remove.
  • index - Optional. Receives the index position of the selector
  • class - Optional. Receives the current class of the selector
switch Optional. A Boolean value specifying if the class should be added (true), or removed (false).


Examples

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.