Add active class to Li on click jquery.

2
Our Reader Score
[Total: 0 Average: 0]
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.

CODE:

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:

 

LIVE DEMO

  


Get your Printable Copy

2 COMMENTS

    • 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.

LEAVE A REPLY