Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match first matching hierarchical descendant with jQuery selectors

[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.

like image 533
Maël Nison Avatar asked Nov 19 '12 05:11

Maël Nison


People also ask

What is the correct way of selecting the current element with jQuery selectors?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Which of the following selects all h1 and h2?

:header Selector Selects all elements that are headers, like h1, h2, h3 and so on.


1 Answers

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)');
like image 199
Ja͢ck Avatar answered Nov 07 '22 11:11

Ja͢ck