Add active class to Li on click jquery.

satinder singh / Updated : / 2 Comments

Overview: Adding a class to List tag  .i.e  li element on click.This article explains how to add class to Li or any HTML tag using jQuery. The most common scenario is to add a class when you click on a menu link and want to make it highlighted. For adding class in jQuery we use .addClass() jquery method.

Prototype: .addClass( className )

Description:  Adds the specified class(es) to each of the set of matched elements.


     $(this).addClass("active");  // adding active class

The above code will add the active class to li whenever li get clicked, You might notice here every time li gets clicked its add active class and this in not what we want to do.

Each time Li gets clicked it remove an active class from li and add it to current clicked li. Yes for this we use removeClass() method check my previous article  How to remove class using jQuery.

So now using removeClass() will remove active class on the previous element, and then using addClass() will add the specific class to the selected element so now our robotic code will look like this:

    // remove classname 'active' from all li who already has classname 'active'
    // adding classname 'active' to current click li 



2 comments on “Add active class to Li on click jquery.”

    • Satinder singh

      Hi Muhannad,
      Yes you are right this can be done in one line code with jQuery Chaining .i.e it allows us to run multiple jQuery methods (on the same element) within a single statement as what you have mentioned in above comment.

      While writing this post, my focus was to make it as simple as possible so the newbie can understand easily.

Post Comment

Your email address will not be published. Required fields are marked *