Daelan
Daelan

Reputation: 723

Add or remove class from all li's in an unordered list except the current li with jQuery

Here is my HTML structure

<ul class="checklist">
    <li class="opaque"><a href="">Link</a></li>
    <li class="transparent"><a href="">Link</a></li>
    <li class="transparent"><a href="">Link</a></li>
</ul>

When I click the anchor within one of the transparent li's I want to set it to opaque and all the other li's within the ul to transparent.

Any ideas on how to do this efficiently?

Upvotes: 1

Views: 9141

Answers (3)

Luca
Luca

Reputation: 1100

How about this solution:

$("li.transparent a").bind("click", function(){
    $("ul.checklist li").attr("class", "transparent");
    $(this).parent().attr("class", "opaque");
});

Upvotes: 0

Michael Haren
Michael Haren

Reputation: 108376

Something like this:

$('.checklist a').click(function(){ 
    $(this).closest('li') // get current LI
       .removeClass('transparent')
       .addClass('opaque')
       .siblings() // get adjacent LIs
         .removeClass('opaque')
         .addClass('transparent');
});

Upvotes: 0

Ken Redler
Ken Redler

Reputation: 23943

You can do something like this:

$('document').ready( function(){
  $('ul.checklist').find('a').click( function(){
    $(this)
      .parent().addClass('opaque').removeClass('transparent')
      .siblings().addClass('transparent').removeClass('opaque');
  });
});

But if you're really only representing two states that never occur together, why not just use one class, the absence of which represents the second state? Then you'd have this:

$('document').ready( function(){
  $('ul.checklist').find('a').click( function(){
    $(this)
      .parent().addClass('opaque')
      .siblings().removeClass('opaque');
  });
});

Upvotes: 7

Related Questions