jammypeach jammypeach - 2 months ago 11
jQuery Question

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?

Answer

Try this:

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