LearnFrenzy
Sign in Take a free test

DOM Manipulation · DOM Coding Problems · Question 8

Print the DOM tree recursively in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The page contains this HTML:

<nav id="site"><ul><li><a href="/">Home</a></li><li class="active"><a href="/practice">Practice</a><ul><li>JS</li></ul></li></ul></nav>

Write a recursive function that prints the element tree under #site with indentation – tag name, id and classes – and returns the deepest nesting level.

Solution
main.js
function printTree(el, depth = 0) {
  const id = el.id ? `#${el.id}` : "";
  const classes = [...el.classList].map((c) => `.${c}`).join("");
  console.log(`${"  ".repeat(depth)}${el.tagName.toLowerCase()}${id}${classes}`);
  let deepest = depth;
  for (const child of el.children) deepest = Math.max(deepest, printTree(child, depth + 1));
  return deepest;
}

const depth = printTree(document.getElementById("site"));
console.log("deepest level:", depth);

Output Verified by running it on Node.js

nav#site
  ul
    li
      a
    li.active
      a
      ul
        li
deepest level: 4

children skips text nodes, so only elements are visited. This depth-first walk is the basis of many DOM interview tasks (find by condition, count nodes, serialise).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links