jQuery toggleClass() Method

jQuery toggleClass() method toggle between add or remove one or more classes from selected elements.

The toggleClass() method accept one or more class names as a parameter.

Syntax

Here is a syntax for toggleClass() method

$(selector).toggleClass( className, function(index, currentclass), state );
Parameter Type Description
className String Required. Add one or more space separated classes to be add or remove.
function(index,currentclass) Function Optional. A function that returns one or more class names to be add or remove.
  • index - Return the index position of the element in the set as an argument.
  • currentclass - Returns the current class name of the element in the set as an argument.
state Boolean Optional. Specifies boolean value that determine whether the class should be added or removed.

Example: Toggle class name

Here, in this example call toggleClass() method

$(document).ready(function() {
  $("button").click(function(){
    $("p").toggleClass("param");
  });
});

Run it...   »

Example: State Parameter

Here, in this example call toggleClass() method along with state parameter

$(document).ready(function() {
  $(".add").click(function(){
    $("p").toggleClass("param", true);
  });
  $(".remove").click(function(){
    $("p").toggleClass("param", false);
  });
});

Run it...   »