Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse the DOM to determine maximum nesting depth?

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

like image 438
api implementor - johnny Avatar asked Dec 03 '22 22:12

api implementor - johnny


1 Answers

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;
}
like image 182
Moazzam Khan Avatar answered Dec 05 '22 10:12

Moazzam Khan