6
<ul>
    <li><a href="#">item 1</a></li>
    <li><a href="#">item 2</a></li>
    <li><a href="#">item 3</a></li>
</ul>

On click, I'd like to addclass active to the parent li element while also removing the active class from any other element which may be active already.

2 Answers 2

6
$("li a").click( function() {
  $(".active").removeClass("active");
  $(this).parent("li").addClass("active");
});
3
  • This will also add the active class to the anchor tag, not the parent li.
    – Matt
    Apr 24, 2010 at 10:22
  • I think it should be $(this).parent().addClass('active') to add the active class to the <li> element? Apr 24, 2010 at 10:23
  • @Nimbuz: You are right. @Matt: you are right, too. Both mistakes fixed.
    – Tomalak
    Apr 24, 2010 at 10:43
2
$('div.filter').delegate('a', 'click', function (event) {
  var theLi = $(this).closest('li');

  theLi.siblings('.active:first').removeClass('active');
  theLi.addClass('active');

  $('ul.items li').hide().filter('.' + this.href.slice(this.href.indexOf("#") + 1)).show();

  event.preventDefault();
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.