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 h
My advice would be to rethink the way you are solving your problem - I think finding the number of generations between nodes probably isn't the best way to go, it sounds like a solution that will be likely to break easily by future changes to the code.
If you insist however, the solution (by Cletus, in native javascript) seems pretty good on this page: find number of nodes between two elements with jquery?
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
function elementDepth(el){
var depth = 0
while(null!==el.parentElement){
el = el.parentElement
depth++
}
return depth
}
console.log(elementDepth(document.getElementById('test')))
<div>
<span id="test">Hi</span>
</div>
It says 3 in this example because it counts the outer <div>
, the <body>
and the <html>
tag.
How about:
$('#my-element').parents().length
Supposing you don't want to include body and html tag in the parents to count use:
$("#element").parents("*").not("body,html").size()
Online demo here: http://jsfiddle.net/zaJff/
Try something like this:
<html>
<head>
<title>MooExample</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("li").click(function() {
alert($(this).parents().length);
});
});
</script>
</head>
<body>
<ul>
<li>moo</li>
<li>foo</li>
<li>fasoo</li>
<li>moasf</li>
<li>moosadg</li>
<li>moo1</li>
<li>moo412</li>
<li>moo613a</li>
</ul>
</body>
</html>