โ† Back to Engine

DOM Navigation & Manipulation


The Document Object Model (DOM) is an object-oriented tree representation of an HTML document, enabling programmatic inspection, modification, and styling of nodes.

1. Nodes vs Elements

  • Node: Base interface (includes Element nodes, Text nodes, Comment nodes, and Document node).
  • Element: Specifically HTML element tags (e.g. DIV, BUTTON). Properties like children filter out whitespace text nodes!

2. DOM Creation Core Methods

  • document.createElement(tag): Creates a new HTML node in memory (e.g. document.createElement('ul')).
  • element.textContent = text: Assigns plain text content inside an element safely.
  • parent.appendChild(child): Appends a child element node as the last child of a parent node.

3. Live vs Static NodeLists

document.getElementsByClassName() returns a Live HTMLCollection that mutates automatically when DOM elements are removed. document.querySelectorAll() returns a Static NodeList snapshot.


The Challenge: Recursive Tree Builder

Implement a function createNestedTree(data) that takes a nested data object and converts it into a nested HTML <ul> / <li> structure.

๐Ÿ’ก STEP-BY-STEP GUIDE & HINTS

  • Hint 1 (Create List Elements): Start by creating a <ul> container and an <li> item using document.createElement().
  • Hint 2 (Set Text & Append): Set li.textContent = data.name, then attach li to ul with ul.appendChild(li).
  • Hint 3 (Handle Nested Children): Check if data.children exists and has items:
    if (data.children && Array.isArray(data.children) && data.children.length > 0)
  • Hint 4 (Recursion): Loop through each child in data.children, call createNestedTree(child), and append the returned sub-tree to li!
  • Hint 5 (Return): Always return the parent ul element at the end of the function.