simonyoung
simonyoung

Reputation: 855

jQuery removeClass on parent/sibling/child

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

Upvotes: 22

Views: 50304

Answers (4)

Jignesh Dalvadi
Jignesh Dalvadi

Reputation: 175

$(this).addClass('active').parent('li').siblings().children().removeClass('active');

Upvotes: 1

vishal
vishal

Reputation: 11

I used above code, it is working

I am using in my code

enter code here : function addnewStepsUpper(){
jQuery('.hide_upper_clone_class').clone().insertAfter(".upper_clone_class1");
jQuery('.upper_clone_class1').siblings().removeClass('hide_upper_clone_class');

}

Thanks Vishal Sanwar

Upvotes: 1

jcolebrand
jcolebrand

Reputation: 16035

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.

Upvotes: 5

Nick Craver
Nick Craver

Reputation: 630597

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');
});

Upvotes: 54

Related Questions