Reputation: 67
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:
Upvotes: 4
Views: 7096
Reputation: 13556
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)
Upvotes: 2
Reputation: 336
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/
Upvotes: 5
Reputation: 3170
An 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;
}
Upvotes: 9
Reputation: 13712
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.
Upvotes: 1