DOM Navigation
In the HTML DOM, navigation allows you to traverse the DOM tree—moving between parent, child, and sibling nodes. Every HTML element, attribute, text, and comment is considered a node, forming a hierarchical structure.
DOM Nodes
According to the W3C DOM standard:
- Document node – The entire document.
- Element nodes – HTML elements (
<div>,<p>,<h1>, etc.). - Text nodes – Text inside elements.
- Attribute nodes – HTML attributes (deprecated).
- Comment nodes – HTML comments (
<!-- comment -->).
Node Relationships
- Root Node: Top node (
<html>). - Parent Node: Node above the current node.
- Child Nodes: Nodes directly under a parent.
- Sibling Nodes: Nodes sharing the same parent.
Example Tree:
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
Navigation Facts:
<html>→ root node, parent of<head>&<body><head>→ first child, parent of<title><title>→ text node child: "DOM Tutorial"<body>→ parent of<h1>&<p>(siblings)
Navigating Between Nodes
| Property | Description |
|---|---|
parentNode | Returns the parent node |
childNodes[n] | Returns all child nodes (including text nodes) |
firstChild | First child node |
lastChild | Last child node |
nextSibling | Next node at the same level |
previousSibling | Previous node at the same level |
firstElementChild | First child element (ignores text nodes) |
lastElementChild | Last child element (ignores text nodes) |
nextElementSibling | Next element sibling |
previousElementSibling | Previous element sibling |
Example:
const h1 = document.getElementById("id01");
console.log(h1.parentNode); // <body>
console.log(h1.nextElementSibling); // <p>Hello world!</p>
console.log(h1.firstChild.nodeValue); // "DOM Lesson one"
Accessing Node Content
innerHTML– Access or modify the content of an element.nodeValue– Value of a text or attribute node.
Examples:
// Using innerHTML
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
// Using nodeValue
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
Special Root Nodes
document.body– Access the<body>element.document.documentElement– Access the<html>root element.
document.getElementById("demo").innerHTML = document.body.innerHTML;
document.getElementById("demo").innerHTML = document.documentElement.innerHTML;
Node Properties
| Property | Description |
|---|---|
nodeName | Name of the node (tag name for elements, #text for text) |
nodeValue | Value of the node (text for text nodes, null for elements) |
nodeType | Type of the node (1=element, 3=text, 8=comment, 9=document) |
Example:
const h1 = document.getElementById("id01");
console.log(h1.nodeName); // H1
console.log(h1.nodeValue); // null (element nodes have null)
console.log(h1.firstChild.nodeValue); // "My First Page"
console.log(h1.nodeType); // 1
