jQuery | toggleClass() with Examples
The toggleClass() method is an inbuilt method in jQuery which is used to toggle or change the class which attached with selected element.
Syntax:
$(selector).toggleClass(class, function, switch)
Parameters: This method accepts three parameters as mentioned above and described below:
- class: It is the required parameter and used to specify the class name need to replace.
- function: It is optional parameter and used to specify a function that returns one or more class names. This parameter contains the index position of element and class name of element.
- switch: It is optional parameter and used to specify either true or false. By default it is true.
Return Value: This method return the selected element with the specified changes made by toggleClass() method.
Below examples illustrate the toggleClass() method in jQuery:
Example 1:
<!DOCTYPE html> <html> <head> <title>The toggleclass Method</title> <script src= </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("div").toggleClass("gfg"); }); }); </script> <style> .gfg { font-size: 25px; background-color: yellow; min-height:120px; } div { width: 200px; min-height: 120px; background-color: lightgreen; padding: 20px; font-weight: bold; font-size: 20px; } </style> </head> <body> <!-- click inside this div element to see the change --> <div> <p>Hello!</p> <p>Welcome to GeeksforGeeks.!</p> <button>Click Here!</button> </div> </body> </html> |
Output:

Example 2:
<!DOCTYPE html> <html> <head> <title>toggle class property</title> <script src= </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("div").toggleClass(function(n) { n = 1; return "item_" + n; }); }); }); </script> <style> .item_1 { color: green; font-weight: bold; font-size: 20px; background-color: white; border: 2px solid green; } div { text-align:center; width: 200px; min-height: 100px; background-color: lightgreen; padding: 20px; border: 2px solid black; font-weight: bold; } </style> </head> <body> <!-- click inside this div element --> <div> <p>Welcome to GeeksforGeeks!</p> <button>Click Here!</button> </div> </body> </html> |
Output:



