XML DOM - navigation node
Node can navigate by using the relationship between nodes.
Navigation DOM node
The relationship between the access node by node node in the tree, commonly referred to as navigation node ( "navigating nodes").
In the XML DOM, the relationship between the nodes is defined as a property of the node:
- parentNode
- childNodes
- firstChild
- lastChild
- nextSibling
- previousSibling
The following image shows books.xml a part of the nodes of the tree, and illustrates the relationship between the nodes:
DOM - parent
All nodes have only one parent. The following code to navigate to the <book> is the parent node:
Examples
x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Get the first <book> element
- Name of the output node "x" parent node
Avoid empty text nodes
Firefox and other browsers, empty, blank or newline as text nodes, while Internet Explorer will not do.
It will use the following attributes: firstChild, lastChild, nextSibling, previousSibling when a problem arises.
To avoid navigating to an empty text nodes (element nodes between the spaces and line breaks), we use a function that checks the node type:
{
y=n.nextSibling;
while (y.nodeType!=1)
{
y=y.nextSibling;
}
return y;
}
The above function allows you to useget_nextSibling(node) instead of thenode .nextSiblingproperty.
Code explanation:
Type 1 is an element node. If the sibling node is not an element node, it moves to the next node, until you find the element nodes so far. By this way, in Internet Explorer and Firefox, you can get the same results.
Being the first child
The following code shows the first <book> is the first element:
Examples
<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:
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Use get_firstChild function on the elements in the first <book>, to get the first child node (an element belonging to the node)
- The output of the first child node (an element belonging to the node) node name
More examples
lastChild ()
This example uses lastChild () method and a custom function to get the last child node
nextSibling ()
This example uses nextSibling () method and the next sibling node of a custom function to get the node
previousSibling ()
This example uses previousSibling () method and a custom function to get a sibling node node