jQuery Add, Remove and Toggle class

jQuery Add, Remove, and Toggle class with Examples

In this article, I am going to discuss jQuery Add, Remove and Toggle class with Examples. Please read our previous article, where we discussed jQuery Insert Elements Before and After. At the end of this article, you will understand everything about how to add, remove and toggle classes using jQuery.

jQuery Add, Remove, and Toggle class

jQuery provides several methods, such as addClass(), removeClass(), toggleClass(), etc. to manipulate the CSS classes assigned to HTML elements.

jQuery addClass() Method:

If you want to add one or more classes to the class attribute of any element. Then jQuery has the method called addClass(). It adds one or more classes to one or more elements simultaneously.
Syntax: $(selector).addClass(classname, function(index, currentclass))
Parameters:
Classname: Required. Specifies one or more class names to be added
Function: Optional. Specifies a function that returns one or more class names to be added. It takes two parameters.

  1. index – Returns the index position of the element in the set
  2. currentclass – Returns the current class name of the selected element
Example: jQuery addClass() Method

In the below example, div1 class is added to every <div> element which is selected when we click on the Add Class button.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Before and After</title>
</head>
<body>
    <h3>jQuery Add and Remove Classes</h3>
    <section>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo addclass">Add Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".addclass").click(function () {
          $("div").addClass("div1");
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab and you can see the div elements without having any classes as shown in the below image.

jQuery Add, Remove, and Toggle class with Examples

Now, click on the Add Class button, and observe that the class div1 is added to the select div elements as shown in the below image.

jQuery Add, Remove, and Toggle class

Adding Multiple Classes using jQuery AddClass Method

To add multiple classes, you can separate the classes by space or you can pass an array of class names.
$(selector).addClass(classname1 classname2) or,
$(selector).addClass([classname1, classname2,…………..])

In the below example, we are adding multiple classes to the div elements.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
</head>
<body>
    <h3>jQuery Add and Remove Class</h3>
    <section>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo addclass">Add Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".addclass").click(function () {
          $("div").addClass("bgcolor font border shadow");
          // $("div").addClass(["bgcolor", "font", "border", "shadow"]);   (You can pass an array)
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab and you can see the div elements without having any classes as shown in the below image.

Adding Multiple Classes using jQuery AddClass Method

Now, click on the Add Class button, and observe that multiple classes are applied to the select div elements as shown in the below image.

Adding Multiple Classes using jQuery AddClass Method with Examples

jQuery AddClass Method Using the callback function

In the below example, the addClass() method is performed by a callback function. Index parameter is receiving the index of the current <div> and currentClass parameter is receiving the present class in the <div>. In this case, test class is present in the <div> element. New classes test0 and test1 are being added to the div elements respectively.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
</head>
<body>
    <h3>jQuery Add and Remove Classes</h3>
    <section>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo addclass">Add Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".addclass").click(function () {
          $("div").addClass(function (index, currentClass) {
            return currentClass + index;
          });
        });
      });
    </script>
</body>
</html>

Now, run the above code and open the browser developer tool by pressing the F12 key and have a look at the Elements tab and you can see currently both the div elements having test class as shown in the below image.

jQuery AddClass Method Using the callback function

Now, click on the Add Class button, and observe that test0 is added to the first div element and test1 is added to the second div element as shown in the below image.

jQuery AddClass Method Using the callback function with Examples

jQuery removeClass() method

If you want to remove one or more classes from the class attribute of any element. Then jQuery has the method called removeClass. It removes one or more classes from one or more elements simultaneously.
Syntax: $(selector).removeClass(classname, function(index, currentclass))
Parameters:
Classname: Required. Specifies one or more class names to be removed
Function: Optional. Specifies a function that returns one or more class names to be removed. It takes two parameters.

  1. index – Returns the index position of the element in the set
  2. currentclass – Returns the current class name of the selected element

Note: If you don’t pass any parameter to removeClass() then it will remove all the classes attached to a specific element.

Example: jQuery removeClass() method

In the below example, notice that we can remove a multiple class from an element (for that we can pass an array also). Or simply if we don’t pass any parameter to the method then it is going to remove all the classes.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
        font-family: Arial, Helvetica, sans-serif;
      }
     h1 {
       font-size: 40px;
       margin-bottom: 30px;
       padding: 30px;
     }

      section {
        background-color: #d1cfcf;
        width: 80%;
        height: auto;
        padding: 10px;
        font-size: 20px;
        font-weight: 200;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        margin-bottom: 20px;
      }
      .demo {
        padding: 8px 20px;
        border-radius: 30px;
        font-size: 18px;
        margin-top: 20px;
        margin-right: 10px;
        border: 1px solid black;
        outline: none;
        transition: 3ms;
      }
      .demo:hover {
        background-color: #ddd;
        cursor: pointer;
      }
       div {
        display: block;
        font-size: 20px;
        margin: 35px;
        padding: 35px;
      }

      .bgcolor {
        background-color: rgb(120, 247, 215);
      }
      .font {
        font-style: italic;
        font-weight: 700;
      }
      .border {
        border: 2px solid black;
        border-radius: 20px;
      }
      .shadow {
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
      }
    </style>
  </head>

<body>
    <h3>jQuery Add and Remove Classes</h3>
    <section>
      <div class="bgcolor font border shadow">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    <button id="remove2" class="demo">Remove Only Border & Shadow</button>
    <button id="removeall" class="demo">Remove All Classes</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#remove2").click(function () {
          $("div").removeClass("border shadow");
        });
        $("#removeall").click(function () {
          $("div").removeClass();
        });
      });
    </script>
</body>
</html>

Now, run the above code and you will see the following output in the browser.

jQuery removeClass() method

Now, click on the ‘Remove only border & shadow’ button and you can see it will remove the border and shadow class and you will get the following output in the browser.

jQuery removeClass() method with Examples

Now, click on the ‘Remove all classes’ button which will remove all the classes and you will get the following output in the browser.

jQuery Add, Remove, and Toggle class with Examples

Example: Remove classes Using the callback function

In the below example, we are removing the ‘test’ class from the div elements if they are indexed at 0 or 3.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
        font-family: Arial, Helvetica, sans-serif;
      }
     h1 {
       font-size: 40px;
       margin-bottom: 30px;
       padding: 30px;
     }

      section {
        background-color: #d1cfcf;
        width: 80%;
        height: auto;
        padding: 10px;
        font-size: 20px;
        font-weight: 200;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        margin-bottom: 20px;
      }
      .demo {
        padding: 8px 20px;
        border-radius: 30px;
        font-size: 18px;
        margin-top: 20px;
        margin-right: 10px;
        border: 1px solid black;
        outline: none;
        transition: 3ms;
      }
      .demo:hover {
        background-color: #ddd;
        cursor: pointer;
      }
       div {
        display: block;
        font-size: 20px;
        margin: 35px;
        padding: 35px;
      }

      .test {
        background-color: rgb(120, 247, 215);
        font-style: italic;
        font-weight: 700;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        border: 2px solid black;
        border-radius: 20px;
      }
    </style>
  </head>

  <body>
    <h1>jQuery Add and Remove Classes</h1>
    <section>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="test">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    </br>
    <button class="demo removeclass">Remove Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".removeclass").click(function () {
          $("div").removeClass(function (index) {
            if (index == 0 || index == 3) {
              return "test";
            } else {
              return "";
            }
          });
        });
      });
    </script>
</body>
</html>

Now, run the above code and you will see the following output in the browser. As you can see in the below image, the class test is applied to all four div elements.

Remove classes Using the callback function in jQuery

Now, click on the ‘Remove classes’ button which will remove the test class from the first and fourth div (index 0 and 3) elements and you will get the following output in the browser.

Remove classes Using the callback function

jQuery toggleClass() Method

The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method adds a class is that is not present and removes the class if that is already present. However, by using the “switch” parameter, you can specify to only remove, or only add a class name.
Syntax: $(selector).toggleClass(classname, function(index, currentclass), switch)
Parameters:
Classname: Required. This is the class name(s) you want to add or remove
Switch: Optional. A Boolean value specifying if the class should only be added (true), or only be removed (false).
Function: Optional. Specifies a function that returns one or more class names that you want to add/remove. It takes two parameters as follows:

  1. index – Returns the index position of the element in the set
  2. currentclass – Returns the current class name of selected elements
Example: jQuery toggleClass() Method

In the below example, we are using the callback function to toggle between the corresponding classes. Here the class we want to toggle is ‘test’ followed by the index. For example, for 1st div, if class .test0 is present then that will be removed and if that is not present then it is going to be added.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
        font-family: Arial, Helvetica, sans-serif;
      }
     h1 {
       font-size: 40px;
       margin-bottom: 30px;
       padding: 30px;
     }

      section {
        background-color: #d1cfcf;
        width: 80%;
        height: auto;
        padding: 10px;
        font-size: 20px;
        font-weight: 200;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        margin-bottom: 20px;
      }
      .demo {
        padding: 8px 20px;
        border-radius: 30px;
        font-size: 18px;
        margin-top: 20px;
        margin-right: 10px;
        border: 1px solid black;
        outline: none;
        transition: 3ms;
      }
      .demo:hover {
        background-color: #ddd;
        cursor: pointer;
      }
       div {
        display: block;
        font-size: 20px;
        margin: 35px;
        padding: 35px;
      }

      .test0,
      .test2 {
        background-color: rgb(120, 247, 215);
        font-style: italic;
        font-weight: 700;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        border: 2px solid black;
        border-radius: 20px;
      }
      .test1,
      .test3 {
        background-color: rgb(255, 219, 102);
        font-style: italic;
        font-weight: 700;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        border: 2px solid black;
        border-radius: 20px;
      }
    </style>
</head>

<body>
    <h1>jQuery Add and Remove Classes</h1>
    <section>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    <button class="demo toggleclass">Toggle Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".toggleclass").click(function () {
          $("div").toggleClass(function (index) {
            return "test" + index;
          });
        });
      });
    </script>
</body>
</html>

Now, run the above code and you will see the following output in the browser.

jQuery toggleClass() Method

Now click on the Toggle Class button and you should get the following output in the browser.

jQuery toggleClass() Method with Examples

jQuery hasClass() Method:

The jQuery hasClass() Method determines that whether a specified class is present in an element or not. It returns a Boolean value.
Syntax: $(selector).hasClass(classname)

Example:

In the below example, for every div element, we are checking for the specified class and then log the same in the Console.

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Add and Remove Class</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
        font-family: Arial, Helvetica, sans-serif;
      }
     h1 {
       font-size: 40px;
       margin-bottom: 30px;
       padding: 30px;
     }

      section {
        background-color: #d1cfcf;
        width: 80%;
        height: auto;
        padding: 10px;
        font-size: 20px;
        font-weight: 200;
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
        margin-bottom: 20px;
        margin: auto;
      }
      .demo {
        padding: 8px 20px;
        border-radius: 30px;
        font-size: 18px;
        margin-top: 20px;
        margin-right: 10px;
        border: 1px solid black;
        outline: none;
        transition: 3ms;
      }
      .demo:hover {
        background-color: #ddd;
        cursor: pointer;
      }
       div {
        display: block;
        font-size: 20px;
        margin: 35px;
        padding: 35px;
      }

      .bgcolor {
        background-color: rgb(120, 247, 215);
      }
      .font {
        font-style: italic;
        font-weight: 700;
      }
      .shadow {
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19),
          0 6px 6px rgba(0, 0, 0, 0.23);
      }
      .border {
        border: 2px solid black;
        border-radius: 20px;
      }
    </style>
</head>

<body>
    <h1>jQuery Add and Remove Classes</h1>
    <section>
      <div class="bgcolor font shadow border">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="bgcolor font shadow">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="bgcolor font">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
      <div class="bgcolor">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nemo, enim
        veritatis ab fugiat ducimus, totam ratione quod
      </div>
    </section>
    <button class="demo hasClass">Has Class</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $(".hasClass").click(function () {
          $("div").each(function (index) {
            console.log(
              `The div at ${index} has bgcolor class : ${$(this).hasClass(
                "bgcolor"
              )}`
            );
            console.log(
              `The div at ${index} has font class : ${$(this).hasClass("font")}`
            );
            console.log(
              `The div at ${index} has shadow class : ${$(this).hasClass(
                "shadow"
              )}`
            );
            console.log(
              `The div at ${index} has border class : ${$(this).hasClass(
                "border"
              )}`
            );
          });
        });
      });
    </script>
</body>
</html>

Now run the above code. Open the browser develop tool by pressing the F12 Key and select the Console tab. Then click on the Has Class button and you should see the following logs in the Console tab.

How to add, remove and toggle classes using jQuery with Examples

Points to Remember:
  1. addClass: It is used to add one or more specified classes. To add multiple classes, we need to separate them with a “space”.
  2. removeClass: It is used to remove one or multiple or all classes. In order to remove multiple classes, we need to separate them with a “space” whereas to remove all classes, we don’t need to specify any class name.
  3. toggleClass: It is used to Toggle one or more specified classes. If the element has the specified class, then it is removed, if the class is not present then it is added.
  4. hasClass: It is used to return true if an element has the specified class otherwise false.

In the next article, I am going to discuss How to use the jQuery Map Methods with Examples. Here, in this article, I try to explain How to add, remove and toggle classes using jQuery with Examples and I hope you enjoy this How to add, remove and toggle classes using jQuery article.

1 thought on “jQuery Add, Remove and Toggle class”

Leave a Reply

Your email address will not be published.