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

jQueryWeb DevelopmentFront End Technology

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>
raja
Published on 15-Dec-2017 10:30:47
Advertisements