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 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:
//*
$("#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");
});
//*
2 comments on “Add active class to Li on click jquery.”
in one line code :
$(this).addClass(“active”).siblings(“li”).removeClass(“active”);
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.