views:

241

answers:

2
<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.

Thanks!

+2  A: 
$("li a").click( function() {
  $(".active").removeClass("active");
  $(this).parent("li").addClass("active");
});
Tomalak
Needed a small fix: ".active". Works perfect, thanks! :)
Nimbuz
This will also add the `active` class to the anchor tag, not the parent li.
Matt
I think it should be $(this).parent().addClass('active') to add the active class to the <li> element?
PeterEysermans
@Nimbuz: You are right. @Matt: you are right, too. Both mistakes fixed.
Tomalak
+1  A: 
$('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();
});
Matt