Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 18 Oct, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

  • The syntax for adding CSS classes to an element:

    $('selector').addClass(class_name);
  • The syntax for Removing CSS classes to an element:



    $('selector').removeClass(class_name);

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.

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=
    </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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!