For example:
// ...
<body>
<div>
<div>
</div>
</div>
</body>
// ...
This nest depth would be 3? But more generally, how can I traverse the DOM to find this information?
I'm interested in treating the DOM like an n-ary tree modeled as an object literal as described in this post:
n-ary tree in JavaScript
For example:
// ...
<body>
<div>
<div>
</div>
</div>
</body>
// ...
This nest depth would be 3? But more generally, how can I traverse the DOM to find this information?
I'm interested in treating the DOM like an n-ary tree modeled as an object literal as described in this post:
n-ary tree in JavaScript
Share Improve this question edited May 23, 2017 at 12:00 CommunityBot 11 silver badge asked Aug 21, 2013 at 17:22 api implementor - johnnyapi implementor - johnny 671 silver badge9 bronze badges 3- Since you don't search for something specific or apply any algorithm to a part of the tree, what's wrong with a simple in-order [full] tree traversal? – Bergi Commented Aug 21, 2013 at 17:27
- that's fine, how would I implement that best? – api implementor - johnny Commented Aug 21, 2013 at 17:29
- Recursively is the simplest. Just try it! – Bergi Commented Aug 21, 2013 at 17:35
4 Answers
Reset to default 9An elegant recursive solution
use this function as in - height(document.body)
function height(el) {
if (!el.children)
return 0;
var max = -1;
for ( var i = 0; i < el.children.length; i++) {
var h = height(el.children[i]);
if (h > max) {
max = h;
}
}
return max + 1;
}
function getMaximumDepth (element) {
var child = element.firstChild;
var childrenDepth = [];
if ( ! child ) {
return 1;
}
while (child) {
childrenDepth.push( getMaximumDepth(child) );
child = child.nextSibling;
}
return Math.max.apply(Math, childrenDepth) + 1;
}
Demo: http://jsfiddle.net/53R2p/
If the only goal is to determine the max nesting level, I'd consider using querySelector
(since it should be well-optimized):
function getMaxNestLevel() {
var i = 1, sel = '* > *'; /* html > body is always present */
while(document.querySelector(sel)) {
sel += ' > *';
i++;
}
return i;
}
Example (with the part of this SO page markup)
My personal favorite is to use a stack. You keep pushing tags until you reach a corresponding/symmetric end tag. Then you can pop or do whatever analysis you'd like to. This is a classic example from a Comp Sci Data Structures class.