Add Class and Remove Class in jQuery


The addclass() method used to add one or more class to the selected Element. removeClass() method used to remove class from the selected Element.

Example :

The following example shows, how to highlight the element when clicked using jQuery addClass() and removeClass() methods.

Demo :

 
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <style>
      .link{
        text-decoration:none;
        margin-top:5px;
        padding:5px;
        color:black;
        display:inline-block
      }
      .active{
        background-color:#000;
        color:white;
      }
    </style>
  </head>
  <body>
    <a href='#' class='link active'>Home</a>
    <a href='#' class='link'>Product</a>
    <a href='#' class='link'>About Us</a>
    <a href='#' class='link'>Contact Us</a>
  <script>
    $(document).ready(function(){
      $(".link").click(function(e){
        e.preventDefault();
        //Remove 'active' class from all 'link' classes.
        $(".link").removeClass("active");
        //Add 'active' class to current 'link' class.
        $(this).addClass("active");
        
      });
    });
  </script>
  </body>
</html>
Try it Yourself