Match first matching hierarchical descendant with jQuery selectors

[edit] I reformulated the question and deleted the example, as it confuses you. Sorry for the trouble.

I need to match the first child that matches the selector.

If several elements match this selector, but they are separated by trees (i.e. if one of them is not the parent of the other), I want to select both of them.

The exact structure of the DOM is unknown, so I cannot use functions like .children( ) or the selector > (because they expect the user to be sure of the actual structure of the DOM).

What I really need is similar to the .closest( ) function, but for matching children instead of parents and possibly multiple children at once.

+6
source share
2 answers

Each tree starting with #B is defined by .children() ; every first .foo inside such a tree .find('.foo:eq(0)') , so you should be able to use this:

 $('#B').children(':not(.foo)').andSelf().find('.foo:eq(0)'); 
+1
source

You can use jQuery closestDescendant plugin

This implements the first width search, so it checks all the children of the current element before it goes down to the next level.

after loading the plugin or adding it to the source code, you can simply call it as follows:

 jQuery('#parent').closestDescendant(".selector", true) 

Here you can find a demo of this function: demo closeestDescendant

0
source

All Articles