I’m trying to select only the first “layer” of children elements of a given type, but not elements nested inside another qualifying element. E.g. in:
<div id='top'>
<div id="s1" class="special">
<div id="s2" class="special"></div>
</div>
<div>
<div id="s3" class="special"></div>
</div>
</div>
I’d like to find #s1 and #s3, but not #s2, with something like $(‘#top’).find(‘.special:not_nested’). Is it possible with jQuery? XPATH?
I thought about jQuery custom filters like expr[‘:’].not_nested, but can’t figure out how to take into account the top parent ($(‘#top’) in this case), because there may be other .special classes further up in the parent chain of #top.
[edit] I should mention right now I’m resorting to a recursive call to $.fn.children() which I think is not very efficient.
[edit2] tested working code:
var node = $('#top'),
result = (node.find('.special').filter(function(){
return !($(this).parent().closest(".special", node).length);
}));
However, this doesn’t work if “#top” has .special class itself. So maybe this:
var node = $('#top'),
result= node.find('.special').filter(function(){
var parent = $(this).parent().closest(".special", node);
return !parent.length || parent.is(node);
});
Another option is to use
.children()in place of.find(), but it will have the same result as idrumgood’s solution.Edit: i just realized the nesting of
#s3, this may work for that situation:Edit2: here ya go: