English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery toggleClass() Method

jQuery HTML/CSS Methods

The toggleClass() method toggles between adding and removing one or more class names for the selected element.

This method checks the specified class name for each element:

  • If the class name is missing, add it

  • If the class name has been set, remove it

However, by usingstateParameters, you can specify to remove or add class names only.

Syntax:

Toggle class name:

$(selector).toggleClass(className)

UsingstateParameters for toggling class:

$(selector).toggleClass(className, state)

Use function to toggle class:

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

Example

Toggle the addition and removal of the 'anotherClass' class name between all <p> elements:

$("button").click(function() {
  $("p").toggleClass("anotherClass");
});
Test to see‹/›

UsingstateParameters only add or remove class names:

$("button").click(function() {
  $("p").toggleClass("anotherClass", true);
});
Test to see‹/›

Parameter Value

ParameterDescription
classNameSpecify to add/One or more (separated by spaces) class names to be removed
stateA boolean value to determine whether to add (true) or remove the class (false)
function(index, currentClass)A function that returns one or more (separated by spaces) class names, which will be added to or removed from the existing class names.
  • index-Return the index position of the element in the collection

  • currentClass-Return the current class name of the selected element

jQuery HTML/CSS Methods