` elements: ``` $("button").click(function(){ $("p").toggleClass("main"); });"> ` elements: ``` $("button").click(function(){ $("p").toggleClass("main"); });" />
Easy Tutorial
❮ Event Focusout Sel Contains ❯

jQuery toggleClass() Method

jQuery HTML/CSS Methods

Example

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

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

Definition and Usage

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

This method checks each element for the specified classes. If the class is not present, it adds the class; if it is already set, it removes it. This is known as a toggle effect.

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


Syntax

Parameter Description
classname Required. Specifies one or more class names to add or remove. To specify multiple 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.<br><br>currentclass - Returns the current class name of the selected element.
switch Optional. A boolean value that specifies whether to only add (true) or only remove (false) the class.

More Examples

Toggle Addition and Removal of Classes

Toggle Classes Using a Function

Using the Switch Parameter


jQuery HTML/CSS Methods

❮ Event Focusout Sel Contains ❯