Ricardo Zea
Ricardo Zea

Reputation: 10283

jQuery: Finding the correct element to remove a class

Ok, somehow I'm just not able to figure out how to make this work, it can't be that difficult.

I have a plain old navigation, like so:

<ul>
        <li><a href="#" class="men-trigger">Men's</a></li>
        <li><a href="#" class="women-trigger">Women's</a></li>
        <li><a href="#" class="coed-trigger">Coed</a></li>
        <li><a href="#" class="all-trigger">All</a></li>
</ul>

And I need to add a class to the clicked element (which I know how to do):

$('.men-trigger').click(function() {  
   $(this).addClass('active');   
});

What I'm having problems with is how to remove the class active from a nav item when another nav item is clicked.

I've tried something like but it doesn't work:

$('.men-trigger').click(function() {  
    $(this).addClass('active');
    $(this).prev().siblings().find('active').removeClass('active');
});

I've tried using .parent().siblings().children();, .parents(ul).find('active'); and I still haven't been able to make it work.

I created a Demo of this.

NOTE: Each nav element needs to have its own class because I'm doing something else in the script, here I'm just showing you the problem I'm having.

Thanks in advance for any help on this.

Upvotes: 1

Views: 159

Answers (4)

adeneo
adeneo

Reputation: 318182

$('.men-trigger').click(function() {  
    $(this).addClass('active').siblings().removeClass('active');
});

Also, you can join all those function with the "ends-with" selector:

$('[class$="trigger"]').click(function() {  
    $(this).addClass('active').siblings().removeClass('active');
});

And since they are nested anchors inside li's, you'll probably have to to:

$('[class$="trigger"]').on('click', function() {  
    $(this).addClass('active').parent('li').siblings().find('a').removeClass('active');
});​

which also adds on() as the preferred way to bind event handlers if using jQuery 1.7+

FIDDLE

Upvotes: 8

pmandell
pmandell

Reputation: 4328

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

Upvotes: 1

Geoff
Geoff

Reputation: 9340

You can use closest to find the parent element. And your find didn't have the "." before active.

$('.men-trigger').click(function() {  
    $(this).closest('ul').find('.active').removeClass('active');
    $(this).addClass('active');
});

Upvotes: 1

Toni Toni Chopper
Toni Toni Chopper

Reputation: 1851

$('.men-trigger').click(function() {  
    $('.active').removeClass('active');
    $(this).addClass('active');
});

assuming you're using the class active only for the nav elements

Upvotes: 1

Related Questions