DOM Tree HeightLoading saved progress…

DOM Tree Height

The DOM is a tree, and a tree has a height: the length of the longest path from the root down to a leaf. It's the same "max depth" problem you'd solve on a binary tree, except each node can have any number of children (element.children), and you count only element nodes. Measuring it is a clean recursion — a leaf is height 0, and any other node is one more than its deepest child.

Implement domTreeHeight(root). Return the height in edges: a single element (no element children) is 0; otherwise it's 1 + max(height of each element child). Count element children only — ignore text and comment nodes.

Signature

function domTreeHeight(root) {
  // returns the number of edges on the longest root-to-leaf path
}

Examples

domTreeHeight(el('<span>hi</span>'));                    // 0 (leaf)
domTreeHeight(el('<div><p><span></span></p></div>'));   // 2 (div → p → span)
domTreeHeight(el('<div><a></a><b></b></div>'));          // 1 (siblings don't add depth)

Notes

  • Height in edges — a leaf is 0, its parent 1, and so on; 1 + max child height for internal nodes.
  • Element children only — use element.children (not childNodes), so text like "hello" doesn't count as depth.
  • Any branching factor — a node can have many children; take the max of their heights, not the sum.
  • Recursion — the natural shape: base case = no children → 0; recursive case = 1 + max(...).
Loading editor…