totallyNotLizards
totallyNotLizards

Reputation: 8569

jquery find() - how to exclude certain descendants, and their children?

I have markup similar to this:

<div class='wrapper plugin'>
    //some content
    <div class='child-wrapper plugin'>
      //some more content
      <div>
        <ul>     
          <li><div class='cliky'>clicky!</div></li>
        </ul>
      </div>
    </div>
  <div class='cliky'>clicky!</div>
</div>

I need to be able to select the first .clicky div only, not any .clicky divs inside a .plugin > .plugin div.

The wrapper has .plugin class too - might seem counter-intuitive so another way to view it is this: I want to get the .clicky children of a given .plugin div, but not .plugin .plugin .clicky.

I've tried selectors like:

$('.wrapper').find('.clicky').not('.plugin > .clicky');

But they still selected all child .clicky elements - including those of the nested .plugin element..

How would I be able to select only the .plugin .clicky elements of a particular .plugin div, but not any .plugin .plugin .clicky elements?

Upvotes: 3

Views: 2328

Answers (3)

Jess&#233; Catrinck
Jess&#233; Catrinck

Reputation: 2277

You can use:

$('.wrapper .cliky').not('.plugin > .plugin .cliky');

or

$('.wrapper .cliky:not(.plugin > .plugin .cliky)');

Tested in jQuery 1.9

Upvotes: 1

Bosworth99
Bosworth99

Reputation: 4234

$('.wrapper').find('.plugin .clicky')[0];

Should return the first element of the "found" array.If you need to incorporate the results in a jquery obj, just reaquire it.

var t = $( $('.wrapper').find('.plugin .clicky')[0]);

Upvotes: 1

Ram
Ram

Reputation: 144719

Try this:

$('.wrapper .clicky').filter(function(){
   return $(this).parents('.plugin').length === 1
})

Upvotes: 4

Related Questions