Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector for grandchildren, or how to anchor the selector on a known element

Let's say I have a hierarchy of elements, with #root at its root. I can use $('#root > * > *') to get all its grandchildren. Is there any way I could do that if I already have $('#root')?

$('#root').find('* > *') is definitely not it, as it will happily "start" from any descendant for the first star, not just #root children.

Is there any function in jQuery that would "anchor" at the current element, starting with its children or itself? It's been bugging me for a while, and I couldn't find anything similar in the docs.

like image 245
Amadan Avatar asked May 30 '12 19:05

Amadan


People also ask

What is Selector by element name?

The name attribute selector can be used to select an element by its name. This selector selects elements that have the value exactly equal to the specified value.

How can I get grandchild in jQuery?

I can use $('#root > * > *') to get all its grandchildren.

What are the selectors of jQuery?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().


1 Answers

Either start the find expression with another > (this syntax is documented):

// This is functionally the same as $('#root > * > *')
$('#root').find('> * > *')

Or call .children() twice: once for its children and again for its grandchildren:

$('#root').children().children()
like image 103
BoltClock Avatar answered Oct 25 '22 17:10

BoltClock