How to use the toggleClass() method In JQuery

The toggleClass() method in jQuery is built to add and remove the class based on the occurrence of an event. It will check whether the class exists in the class list or not. If the class is there in the list it will remove the class from there. Otherwise, it will add the class to the element.

Syntax:

$('element_selector').toggleClass('className');

Example: The below example will explain the use of the toggleClass() method to add and remove the class from an HTML element.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
 
    <!-- Including jQuery  -->
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js"
            integrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous">
    </script>
 
    <style>
        h1 {
            color: #006600;
        }
        button {
            color: white;
            background-color: #006600;
            width: auto;
            height: 30px;
        }
        div {
            margin: 2rem;
            text-align: center;
        }
        #GFG_IMAGE{
            position: relative;
            transition: transform 0.5s ease-in;
            transform-style: preserve-3d;
        }
        .flip {
            transform: rotateY(180deg);
        }
    </style>
</head>
 
<body>
    <center>
        <h1>w3wiki</h1>
        <h3>Flip the image by adding the .flip class</h3>
        <button id="toggleBtn"> Toggle Class </button>
        <div id="GFG_IMAGE">
            <!-- Image added using img tag
                with src attribute -->
            <img src=
"https://media.w3wiki.org/wp-content/uploads/20231212145751/gfgImage.png"
                height='150px' width='150px'>
            <img>
        </div>
    </center>
    <script>
        $(document).ready(function() {
            $('#toggleBtn').click(function() {
                $('#GFG_IMAGE').toggleClass('flip');
            });
        });
    </script>
</body>
 
</html>


Output:



How to Add or Remove class in jQuery ?

In this article, we are going to learn about the different methods to add and remove classes from an HTML element using jQuery. There are two ways in which we can achieve this in jQuery.

Table of Content

  • Using the addClass() and removeClass() methods
  • Using the toggleClass() method

Similar Reads

Using the addClass() and removeClass() methods

The addClass() and removeClass() methods are respectively used to add and remove the CSS classes when there is a need to add or remove them from the webpage on the occurrence of an event....

Using the toggleClass() method

...

Contact Us