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


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.


     $(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 removes 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:

    // remove classname 'active' from all li who already has classname 'active'
    $("#navMenus li.active").removeClass("active"); 
    // adding classname 'active' to current click li 


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 thank me? 👳 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 *