What is the difference between switchClass() and toggleClass() methods in jQuery?


The switchClass() is used to switch class from an element. Use it, to replace one class with another. Add jQuery UI library to the web page to use switchClass().

Example

You can try to run the following code to learn how to work with switch class −

Live Demo

<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
          $("a").click(function(){
             $("a.active").removeClass("active");
             $(this).addClass("active");
           });
         });
      </script>
      <style>
         .active {
            font-size: 22px;  
         }
      </style>
   </head>
   <body>
      <a href="#" class="demo1">One</a>
      <a href="#" class="demo2">Two</a>
      <p>Click any of the link above and you can see the changes.</p>
   </body>
</html>

Toggle Class

If you want to toggle between classes, then use the toggleClass(). This is to add or remove classes from the selected elements.

Example

You can try to run the following code to learn how to toggle class −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, p").toggleClass("blue");
    });
});
</script>
<style>
.blue {
    color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<p>This is demo text.</p>

<button>Toggle</button>

</body>
</html>

Updated on: 14-Feb-2020

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements