jQuery Tutorial

jQuery toggleClass() Method With Syntax and Example

Understanding toggleClass method in jQuery

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

This method looks for the specified class names in each element. If the class names are missing, they are added, and if they are already set, they are removed, creating a toggle effect.

Using the "switch" parameter, you can specify whether only to remove or add a class name.

Syntax of toggleClass method in jQuery

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

Example of jQuery toggleClass method

For all

elements, toggle between adding and removing the "main" class name:

$("button").click(function(){
  $("p").toggleClass("main");
});
Did you find this article helpful?