With the HTML DOM, you can traverse the node tree using the relationships between nodes.
According to the W3C HTML DOM standard, everything in an HTML document is considered a node:
With the HTML DOM, JavaScript can access all nodes in the node tree.
It allows for the creation of new nodes, as well as the modification or deletion of existing ones.
In the node tree, nodes have a hierarchical relationship:
<html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html> |
From the HTML structure, we can observe the following:
<html>
is the root node.<html>
has no parent.<html>
is the parent of <head>
and <body>
.<head>
is the first child of <html>
.<body>
is the last child of <html>
.Additionally:
<head>
has one child: <title>
.<title>
has one child (a text node): “DOM Tutorial”.<body>
has two children: <h1>
and <p>
.<h1>
has one child: “DOM Lesson One”.<p>
has one child: “Hello World!”.<h1>
and <p>
are siblings.You can navigate between nodes in the DOM using the following JavaScript node properties:
parentNode
– Accesses the parent node of the current node.childNodes[nodenumber]
– Retrieves a specific child node by its index.firstChild
– Returns the first child node of the current node.lastChild
– Returns the last child node of the current node.nextSibling
– Accesses the next sibling node of the current node.previousSibling
– Retrieves the previous sibling node of the current node.A common mistake in DOM processing is assuming that an element node directly contains text, when in fact the text is typically stored in a separate text node. |
<title id=”demo”>DOM Tutorial</title> |
The <title> element node (in the example above) does not directly contain text.
Instead, it contains a text node with the value “DOM Tutorial.” The value of the text node can be accessed through the node’s innerHTML property.
myTitle = document.getElementById(“demo”).innerHTML; |
Accessing the innerHTML property is equivalent to accessing the nodeValue of the first child node.
myTitle = document.getElementById(“demo”).firstChild.nodeValue; |
You can also access the first child in this way:
myTitle = document.getElementById(“demo”).childNodes[0].nodeValue; |
All three of the following examples retrieve the text from an <h1> element and copy it into a <p> element:
<html> <body> <h1 id=”id01″>My First Page</h1> <p id=”id02″></p> <script> document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).innerHTML; </script> </body> </html> |
<html> <body> <h1 id=”id01″>My First Page</h1> <p id=”id02″></p> <script> document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).firstChild.nodeValue; </script> </body> </html> |
<html> <body> <h1 id=”id01″>My First Page</h1> <p id=”id02″>Hello!</p> <script> document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).childNodes[0].nodeValue; </script> </body> </html> |