jQuery add active class to ul li menu tag on click.

/ / 2 Comments

jQuery add active class to the menu: Adding a class to List tag  .i.e  li element on button click. This article explains how to add a 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 active or highlighted. That is make the link active or inactive. For adding class in jQuery we use .addClass() method.



Prototype: .addClass( className )

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

CODE:

$("#navMenus").on('click','li',function(){
     $(this).addClass("active");  // adding active class
});

The above code will add the active class to the li tag whenever the user clicks on the Li element. You might notice here every time li gets clicked it adds an active class and this is not what we want to do. Each time the Li tag gets clicked it remove an active class from all other li items and add it to the current clicked LI. Yes for this we use removeClass() method to check my previous article.  

How to remove class using jQuery?

So now using the removeClass() method will remove the active class on the previously selected menu, and then using the addClass() method will add the specific class to the currently selected menu li element.

So now our robotic code will look like this:

//*
$("#navMenus").on('click','li',function(){
    // remove classname 'active' from all li who already has classname 'active'
    $("#navMenus li.active").removeClass("active"); 
    // adding classname 'active' to current click li 
    $(this).addClass("active"); 
});
//*
 

LIVE DEMO

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

2 Comments

  1. Muhannad 01/10/2016 20:45:55
    in one line code : $(this).addClass(active").siblings("li").removeClass("active");"
  2. Satinder singh 01/11/2016 15:11:50
    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.