Open In App

How to add and remove CSS classes to an element using jQuery ?

In this article, we will see how to add or remove the CSS classes to an element using jQuery. To add the CSS classes to an element we use addClass() method, and to remove the CSS classes we use removeClass() method.

Syntax:



Example: In the this example, we first create an image element and two buttons, the first button for adding CSS classes and the second button for removing CSS classes. When users click on the first button, the addClass() method is called and the class is added to the image element. When the user clicks on the second button, the removeClass() method is called and the class is removed from the image element.




<!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=
    </script>
  
    <style>
        button {
            padding: 5px 15px;
            background-color: green;
            color: white;
        }
  
        .bg-black {
            background-color: black;
        }
    </style>
</head>
  
<body style="text-align: center">
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to add and remove CSS classes
        to an element using jQuery?
    </h3>
  
    <div id="GFG_IMAGE">
        <img src=
            height="200px" width="250px" />
    </div>
  
    <br />
    <button id="addCls">
        Add CSS Class
    </button>
    <button id="removeCls">
        Remove CSS Class
    </button>
  
    <script>
        $(document).ready(function () {
            $("#addCls").click(function () {
                $("img").addClass("bg-black");
            });
            $("#removeCls").click(function () {
                $("img").removeClass("bg-black");
            });
        });
    </script>
</body>
  
</html>

Output:


Article Tags :