The DOM Tree
When a browser loads an HTML page, it creates a tree structure called the DOM (Document Object Model). Each HTML element becomes a node in this tree.
document
β
html
β± β²
head body
β± β β± β²
title meta h1 nav
β β± β²
"Page" a a
Every HTML Element is a Node
The DOM represents everything as a node:
| Node Type | Example | nodeType |
|---|---|---|
| Element node | <h1>, <p>, <div> | 1 |
| Text node | βHello Worldβ | 3 |
| Comment node | <!-- comment --> | 8 |
| Document node | document | 9 |
Demo: Exploring the DOM Tree
HTML
<div id='tree-demo'>
<h1>Hello</h1>
<p>This is a <strong>paragraph</strong> with text.</p>
<!-- This is a comment -->
</div> JavaScript
const div = document.getElementById('tree-demo');
const output = document.createElement('pre');
output.style.cssText = 'background:#f1f5f9;padding:12px;border-radius:6px;font-size:14px;';
function walkTree(node, depth = 0) {
let indent = ' '.repeat(depth);
let info = '';
if (node.nodeType === 1) {
info = `<${node.tagName.toLowerCase()}>`;
} else if (node.nodeType === 3) {
let text = node.textContent.trim();
if (text) info = `${text}`;
} else if (node.nodeType === 8) {
info = `<!-- ${node.nodeType} -->`;
}
if (info) output.innerHTML += indent + info + '\\n';
for (let child of node.childNodes) {
walkTree(child, depth + 1);
}
}
walkTree(div);
div.parentNode.replaceChild(output, div); Live Output Window
The Document Node
document is the entry point to the DOM. From it, you can reach any element:
document.documentElement // the <html> element
document.head // the <head> element
document.body // the <body> element
document.title // the page title
Children: Elements vs Nodes
A key distinction:
- Child nodes β all children (elements, text, comments)
- Children elements β only HTML element children
Demo: Nodes vs Elements
HTML
<ul id='list'>
<li>Item 1</li>
<li>Item 2</li>
<!-- Comment -->
<li>Item 3</li>
</ul> JavaScript
const ul = document.getElementById('list');
const out = document.getElementById('output') || (() => {
const p = document.createElement('p'); p.id = 'output';
ul.after(p); return p;
})();
out.innerHTML =
'childNodes count: ' + ul.childNodes.length + ' (includes text & comments)<br>' +
'children count: ' + ul.children.length + ' (only <li> elements)'; Live Output Window
Key Takeaways
- The DOM is a tree with nodes for every HTML element, text, and comment
documentis the root β everything starts therechildNodesincludes all node typeschildrenincludes only elements- Understanding the tree helps you navigate and manipulate pages effectively