Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery removeClass on parent/sibling/child

Tags:

jquery

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

like image 398
simonyoung Avatar asked Oct 19 '10 21:10

simonyoung


2 Answers

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');
});
like image 146
Nick Craver Avatar answered Oct 24 '22 08:10

Nick Craver


Also note that if you want to remove 'active' from all elements except this then you could get away with something as simple as

$('.active').removeClass('active');
$(this).addClass('active');

And that should propagate through the tree pretty easily. However, I can see it causing a headache on performance if the DOM is heavily populated.

like image 5
jcolebrand Avatar answered Oct 24 '22 08:10

jcolebrand