Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS/jQuery: Get depth of element?

What's the easiest way to get the depth of an element in pure JavaScript or jQuery? By "depth" I mean how many elements deep is it nested, or how many ancestors does it have.

like image 513
mpen Avatar asked Jan 17 '11 07:01

mpen


2 Answers

How about:

$('#my-element').parents().length
like image 155
polarblau Avatar answered Oct 19 '22 17:10

polarblau


An additional note. If you want to get the depth relative to a certain context you can do:

var depth = $("#my-element","#ContextContainerID").parents("ul").length;

Above, I'm searching for how many UL's are within the container #ContextContainerID

like image 9
Fostah Avatar answered Oct 19 '22 18:10

Fostah