HTML DOM Navigation
Through the HTML DOM, you can navigate the node tree using node relationships.
HTML DOM Node List
The getElementsByTagName() method returns anode list. A node list is an array of nodes.
The following code selects all
nodes in the document:
Example
var
x
=
document
.
getElementsByTagName
(
"
p
"
)
;
These nodes can be accessed by index number. To access the second
node, you can write:
y
=
x
[
1
]
;
Try it »
Note:
Index numbers start at 0.
HTML DOM Node List Length
The length property defines the number of nodes in a node list.
You can use the length property to loop through a node list:
Example
x
=
document
.
getElementsByTagName
(
"
p
"
)
;
for
(
i
=
0
;
i
<
x
.
length
;
i
++
)
{
document
.
write
(
x
[
i
]
.
innerHTML
)
;
document
.
write
(
"
"
)
;
}
Try it »
Example analysis:
- Get all
element nodes
- Output each
element's text node value
Navigate Node Relationships
You can use three node properties: parentNode, firstChild, and lastChild, to navigate the document structure.
See the HTML snippet below:
<html>
<head>
<meta charset="utf-8" head>
<body>
<p>Hello World!
p
<
div
<
pDOM is very useful!
p
<
p
This example demonstrates the relationships between nodes.
p
div
body
html
- The first
element is the first child element of the element (firstChild)
-
element is the last child element of the element (lastChild)
- element is the first
element and
element's parent node (parentNode)
The firstChild property can be used to access the text of an element:
Example
<p id="intro">Hello World!
p
<
script
x=document.getElementById("intro"); document.write(x.firstChild.nodeValue);
script
Try it »
DOM Root Node
Here are two special properties that can access the entire document:
- document.documentElement - the entire document
- document.body - the body of the document
Example
<
p
Hello World!
p
<
div
<
pDOM is very useful!
p
<
p
This example demonstrates the
<
b
document.body
battribute.
p
div
<
script
alert(document.body.innerHTML);
script
Try it »
childNodes and nodeValue
In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following code gets the element with id="intro"
element's value:
Example
<p id="intro">Hello World!
p
<
script
txt=document.getElementById("intro").childNodes[0].nodeValue; document.write(txt);
script
Try it »
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial, we will use the innerHTML property. However, learning the method above helps with understanding the DOM tree structure and navigation.