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 likechildrenfilter 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 usingdocument.createElement(). - Hint 2 (Set Text & Append): Set
li.textContent = data.name, then attachlitoulwithul.appendChild(li). - Hint 3 (Handle Nested Children): Check if
data.childrenexists and has items:if (data.children && Array.isArray(data.children) && data.children.length > 0) - Hint 4 (Recursion): Loop through each child in
data.children, callcreateNestedTree(child), and append the returned sub-tree toli! - Hint 5 (Return): Always return the parent
ulelement at the end of the function.