What is the DOM Tree?
The DOM (Document Object Model) is a structured representation of an HTML or XML document. JavaScript uses the DOM to interact with and manipulate web pages dynamically.
When a web page is loaded, the browser parses the HTML and builds a tree-like structure of objects called the DOM Tree. Each HTML element becomes a node in this tree, allowing JavaScript to traverse and modify them easily.
Visualizing the DOM Tree Structure
Imagine the following HTML code (just for reference, no need to write or run this in JavaScript):
<html>
<body>
<div>
<p>Hello World</p>
</div>
</body>
</html>
This HTML is turned into a tree like this:
- html
- body
- div
- p (text: "Hello World")
- div
- body
Accessing the DOM Tree in JavaScript
You can inspect and interact with this structure using JavaScript from your browser's console or in Node (with some setup). Here are some examples.
Example 1: Accessing the Root Node
// This will return the root of the document
console.log(document.documentElement);
Output:
<html>...</html>
Question: What does document.documentElement
return?
Answer: It returns the top-level <html>
element of the DOM tree.
Example 2: Navigating Child and Parent Nodes
const body = document.body;
console.log(body.parentNode); // should be the HTML element
console.log(body.childNodes); // shows child nodes including text, comments, elements
Output:
<html>...</html> NodeList(3) [text, div, text]
Example 3: First and Last Child
const firstChild = document.body.firstChild;
const lastChild = document.body.lastChild;
console.log(firstChild);
console.log(lastChild);
Question: Why might the first or last child be a text node?
Answer: Because whitespace between HTML tags is considered a text node in the DOM.
Example 4: Traversing the DOM
// Traverse from body to its children
for (let node of document.body.childNodes) {
console.log("Node Type:", node.nodeType);
console.log("Node Name:", node.nodeName);
}
Output:
Node Type: 3 Node Name: #text Node Type: 1 Node Name: DIV Node Type: 3 Node Name: #text
Example 5: Difference Between childNodes and children
const allNodes = document.body.childNodes; // Includes text nodes
const elementChildren = document.body.children; // Only elements
console.log("All nodes:", allNodes.length);
console.log("Only element nodes:", elementChildren.length);
Question: When should you use children
over childNodes
?
Answer: Use children
when you only care about HTML elements and want to ignore text nodes.
Summary
- The DOM Tree represents your page structure in memory.
- Every element, attribute, and piece of text is a node.
- You can access, traverse, and manipulate these nodes using JavaScript.
Try This Yourself
// Print all element names under the body
for (let el of document.body.children) {
console.log(el.tagName);
}
This helps build intuition about the elements currently inside the body
of your web page.