Chris
Chris

Reputation: 170

How can I target elements whose classes don't contain the ID of this element?

Specifically, I want to say: for elements whose class value doesn't contain this element's ID value, execute this function.

For example, clicking #foo will execute fadeOut() on the list items whose classes don't contain .foo in the following HTML:

<button id="foo">foo</button>
<button id="bar">bar</button>
<button id="baz">baz</button>
<ul>
    <li class="foo">Lorem</li>
    <li class="foo bar">Ipsum</li>
    <li class="baz">Dolor</li>
</ul>

So upon clicking #foo, the last list item should disappear, since the first two both contain the .foo class.

Upvotes: 5

Views: 103

Answers (3)

Ulises
Ulises

Reputation: 13419

You need to select the buttons somehow so you can attach your event. Then you will need to extract the id and select those that do NOT contain that class. Here is an example using the not method:

 $(':button').click(function(){
  $('li').not('.' + $(this).attr('id')).fadeOut(); 
});

http://jsfiddle.net/ureyes84/Fr7dm/2/

Upvotes: 0

Dirk Boer
Dirk Boer

Reputation: 9065

You can use the not selector: http://api.jquery.com/not-selector/

$('#foo').click(function() {
    $('li').not('.foo').fadeOut();
});​

see:

http://jsfiddle.net/dSSza/

Upvotes: 0

Musa
Musa

Reputation: 97672

Try

$('button').on('click', function(){
    $('li:not(.'+this.id+')').fadeOut();
});

Demo

Upvotes: 5

Related Questions