toggleClass() method in jQuery

toggleClass() in jQuery

toggleClass() method is used to toggle between adding or removing the class name of the specified element.

This method will remove the specified class name if it is already present in the element.

This method will add the specified class name if it is not present in the element.

Syntax 1

$(selector).toggleClass(className[,state])

  • className - One or more class names separated by spaces, which are to be toggled.
  • state - A boolean value to determine whether the class should be added or removed.

Syntax 2

$(selector).toggleClass(function(index,currentClass)[,state])

  • index - index position of the element in the set.
  • currentClass - Existing class name(s).
  • state - A boolean value to determine whether the class should be added or removed.

Example 1

Try Yourself

Example 2 - Force to only add class

Try Yourself

Example 3 - used with function

Try Yourself

Example 4 - used with function and force status is true

Try Yourself