Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add class to current li and remove prev li when click inside li a

Tags:

html

jquery

here is html:

<ul>    
    <li class="current"><a href="#">menu item</a></li>  
    <li><a href="#aba">menu item</a></li>
    <li><a href="#abb">menu item</a></li>
    <li><a href="#abc">menu item</a></li>
    <li><a href="#abd">menu item</a></li>
</ul>

if I press 'a' link it will addClass 'current' to clicked li and remove old li class? this is my try:

$('ul li a').click(function(){
  $('ul li').removeClass('current');
  ... don't know here (add class to current li) ...
});
like image 245
test Avatar asked Mar 13 '12 17:03

test


People also ask

What is addClass and removeClass in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do I add active class to UL Li?

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.

Which jQuery method is used to switch between adding removing one or more classes from selected elements?

jQuery toggleClass() Method The toggleClass() method toggles between adding and removing one or more class names from the selected elements.


1 Answers

Use on('click') if you are using latest version of jquery

$('ul li a').on('click', function(){
    $(this).parent().addClass('current').siblings().removeClass('current');
});

A fiddle is here.

like image 136
The Alpha Avatar answered Sep 22 '22 11:09

The Alpha