XML DOM - Navigating Nodes
Nodes can be navigated using the relationships between nodes.
Navigating DOM Nodes
Accessing nodes in the node tree through relationships between nodes is commonly referred to as navigating nodes ("navigating nodes").
In the XML DOM, the relationships between nodes are defined as node properties:
- parentNode
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
The following image shows a part of the node tree from books.xml and illustrates the relationships between nodes:
DOM - Parent Node
All nodes have only one parent node. The following code navigates to the parent node of <book>:
Example
xmlDoc = loadXMLDoc("books.xml");
x = xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);
Example explanation:
- Use loadXMLDoc() to load "books.xml" into xmlDoc
- Get the first <book> element
- Output the node name of the parent node of "x"
Avoiding Empty Text Nodes
Firefox and some other browsers treat empty whitespace or line breaks as text nodes, while Internet Explorer does not.
This can cause an issue when using properties like firstChild, lastChild, nextSibling, and 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 above function allows you to use get_nextSibling(node) instead of node.nextSibling.
Code explanation:
The type of an element node is 1. If the sibling node is not an element node, move to the next node until an element node is found. This way, you get the same result in both Internet Explorer and Firefox.
Getting the First Child Element
The following code displays the first element of the first <book>:
Example
<html>
<head>
<script src="loadxmldoc.js"></script>
<script>
// Check if 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
Example explanation:
- Use loadXMLDoc() to load "books.xml" into xmlDoc
- Use the get_firstChild function on the first <book> 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)