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).
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!