jQuery Attribute Manipulation - toggleClass() Method

Example

Toggle the addition and removal of the "main" class for all <p> elements:

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

Try It Yourself

Definition and Usage

The toggleClass() method toggles the addition or removal of one or more classes for the selected elements.

This method checks each element for the specified class. If it does not exist, it adds the class, and if it is already set, it removes it. This is what is called the toggle effect.

However, by using the "switch" parameter, you can specify to add or remove classes only.

Syntax

$().toggleClass(class,switch)
Parameters Description
class

Required. Specifies the element to add or remove the class from.

If you need to specify multiple classes, use spaces to separate class names.

switch Optional. Boolean value. Specifies whether to add or remove the class.

Use a function to toggle class

$().toggleClass(function(index,class),switch)

Try It Yourself

Parameters Description
function(index,class)

Required. Specifies a function that returns one or more class names to be added or removed.

  • index - Optional. Accepts the index position of the selector.
  • class - Optional. Accepts the current class of the selector.
switch Optional. Boolean value. Specifies whether to add (true) or remove (false) the class.