jQuery toggleClass()Methods

jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Examples

Toggles adding and removing the "main" class for all <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 from selected elements.

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

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


Syntax

$(selector).toggleClass(classname,function(index,currentclass),switch)

Parameter 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.
  • index- Returns the index position of the element in the set.
  • currentclass- Returns the current class name of the selected element.
switch Optional. A Boolean value specifying whether to only add (true) or remove (false) the class.


实例

More Examples

Toggle between adding and removing classes
How to use the toggleClass() method to toggle adding and removing classes.

Toggle classes using a function
Use a function to specify which class name the current element needs to toggle.

Use the switch parameter
How to use the switch parameter to only add or remove class names.


jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Other extensions