XML DOM - Navigating Nodes
Nodes can be navigated by using the relationships between nodes.
Navigating DOM Nodes
Accessing nodes in the node tree through the relationships between nodes is usually called navigating nodes ("navigating nodes").
In the XML DOM, node relationships are defined as properties of the nodes:
- parentNode
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
The following image shows books.xml a part of the node tree, and illustrates the relationships between the nodes:

DOM - Parent Nodes
Every node has only one parent. The following code navigates to
Example
xmlDoc
=
loadXMLDoc
(
"
books.xml
"
)
;
x
=
xmlDoc
.
getElementsByTagName
(
"
book
"
)
[
0
]
;
document
.
write
(
x
.
parentNode
.
nodeName
)
;
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
Element - Output the node name of "x"'s parent node
Avoid Empty Text Nodes
Firefox and some other browsers treat empty whitespace or line breaks as text nodes, while Internet Explorer does not.
This causes a problem when using the following properties: firstChild, lastChild, nextSibling, previousSibling.
To avoid navigating to empty text nodes (spaces and line breaks between element nodes), we use a function to check the node type:
function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
The function above allows you to use get_nextSibling (node) instead of nodethe .nextSibling property.
Code Explanation:
The type of an element node is 1. If a sibling node is not an element node, move to the next node until an element node is found. In this way, the same result is obtained in both Internet Explorer and Firefox.
Get the First Child Element
The following code shows the first
Example
<html>
<head>
<script src="loadxmldoc.js" script>
<script//>Check whether the first node is an element node
function
get_firstChild
(
n
)
{
y
=
n
.
firstChild
;
while
(
y
.
nodeType
!=
1
)
{
y
=
y
.
nextSibling
;
}
return
y
;
}
script
head
<body> <script xmlDoc=loadXMLDoc("books.xml" )>;
x
=
get_firstChild
(
xmlDoc
.
getElementsByTagName
(
"
book
"
)
[
0
]
)
;
document
.
write
(
x
.
nodeName
)
;
script
body
html
Output:
title
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- In the first
use the get_firstChild function on the element to get the first child node (which is an element node) - Output the node name of the first child node (which is an element node)
More examples
lastChild()
This example uses the lastChild() method and a custom function to get the last child node of a nodenextSibling()
This example uses the nextSibling() method and a custom function to get the next sibling node of a nodepreviousSibling()
This example uses the previousSibling() method and a custom function to get the previous sibling node of a node