Open In App

jQuery toggleClass() Method

The toggleClass() method is an inbuilt method in jQuery that is used to toggle or change the class attached to the selected element.

Syntax:



$(selector).toggleClass(class, function, switch)

Parameters:

This method accepts three parameters as mentioned above and described below:



Return Value: This method returns the selected element with the specified changes made by the toggleClass() method.

The 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:


Article Tags :