0

I have this list in my HTML:

<ul>
    <li class="active"></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Here I want that only the clicked <li> should have class set as "active". Hence when someone clicks on second <li> element that should be set with class as active and the first should be removed.

How can do this using jQuery?

3 Answers 3

4

Try this:

$('ul li').click(function(){
     $(this).addClass('active').siblings().removeClass('active')
})
Sign up to request clarification or add additional context in comments.

Comments

2

Remove the class from the selected element and add the new:

$('li').click(function(){
  $('li.active').removeClass('active');
  $(this).addClass('active');
});

Comments

1
$('ul').on('click','li',function(){
    $(this).addClass('active').siblings().removeClass('active');
});​

Try the demo here.

In this method only one click listener will be added to the ul element. It's good for your performance.

I hope this will solve your problem. If you have any questions please don't hesitate to ask. Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.