Reputation: 7353
[edit] I have reworded the question and removed the example, since it seems to confuse you. Sorry for trouble.
I need to match the first descendant which match a selector.
If multiple elements match this selector but are in separates trees (i.e. if one is not the parent of another) then I want to select both of them.
The exact DOM structure is not known, so I can't use functions like .children( )
or the >
selector (because they expect the user to be sure about the actual DOM structure).
What I need actually look like the .closest( )
function, but for matching children instead of parents, and potentially multiple children at once.
Upvotes: 6
Views: 2368
Reputation: 50090
You could use the jQuery Plugin closestDescendant
That implemenst a breadth first search, so its checks all children of current element befor it goes down to the next level.
after loading plugin or adding it to you source code you could simple call it in this way:
jQuery('#parent').closestDescendant(".selector", true)
Here you can find a demo of that function: demo closestDescendant
Upvotes: 0
Reputation: 173572
Every tree starting from #B
is defined by .children()
; every first .foo
within such a tree is .find('.foo:eq(0)')
, so you should be able to use this:
$('#B').children(':not(.foo)').andSelf().find('.foo:eq(0)');
Upvotes: 1