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

1

19

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.

Otherdirected answered 30/5, 2012 at 19:48 Comment(1)
.find() is possibly the single most annoying jQuery traversal method, ever.Idealistic
I
34

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()
Idealistic answered 30/5, 2012 at 19:50 Comment(5)
Yeah, I knew about the .children() thing, but... well, doesn't fit what I'm doing, I really wanted the selector thing. And the selector thing... wow, I never thought to try that, that's amazing. Any idea how solid it is? I'm a bit wary of it being undocumented - works now, but for how long?Otherdirected
@Amadan: I have no idea about that... it seems to have worked for quite some time now.Idealistic
I've updated this post to reflect that this feature is now documented.Voleta
@JDB: About time it did. Thanks!Idealistic
Thanks, really helpful :)Marie

© 2022 - 2024 — McMap. All rights reserved.