Clean β’ Professional
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.
According to the W3C DOM standard:
<div>, <p>, <h1>, etc.).<!-- comment -->).<html>).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)| 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"
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;
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;
| 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
Β