Alex Rivera | Logout

jQuery removeClass on parent/sibling/child

Asked 2010-10-19T21:29:11.457
22

I am using the following jQuery to change classes on elements in an unordered list. It doesn't seem like it is the most effective way of achieving the effect. Is there a better way to write this?

$(function() {
    $('nav li a').click( function() {
        $(this).parent().siblings().children().removeClass('active');
        $(this).addClass('active');
    });
});

Thanks

S

Edit
Report

1 Answer

54

It's usually simpler in these cases to attach the handler to the <li> and let the click bubble up from the <a> (which happens by default). Then your handler looks like this:

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

Then in your CSS you just account for active being on the <li>, like this:

li.active a { color: red; }

As an aside, if you have many <li> elements you'll want to use .delegate() like this:

$('nav').delegate('li', 'click', function() {
  $(this).addClass('active').siblings().removeClass('active');
});
answered 2010-10-19T21:31:52.010

Your Answer