With the DOM, you can access every node in an XML document.
Access a node using its index number in a node list
This example uses the getElementsByTagname() method to get the third <title> element in "books.xml"
Loop through nodes using the length property
This example uses the length property to loop through all <title> elements in "books.xml"
See the node type of an element
This example uses the nodeType property to get node type of the root element in "books.xml".
Loop through element nodes
This example uses the nodeType property to only process element nodes in "books.xml".
element nodes using node relationships
This example uses the nodeType property and the nextSibling property to process element nodes in "books.xml".
You can access a node in three ways:
1. By using the getElementsByTagName() method
2. By looping through (traversing) the nodes tree.
3. By navigating the node tree, using the node relationships.
getElementsByTagName() returns all elements with a specified tag name.
The following example returns all <title> elements under the x element:
Note that the example above only returns <title> elements under the x node. To return all <title> elements in the XML document use:
where xmlDoc is the document itself (document node).
The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The <title> elements in x can be accessed by index number. To access the third <title> you can write::
Note: The index starts at 0.
You will learn more about node lists in a later chapter of this tutorial.
The length property defines the length of a node list (the number of nodes).
You can loop through a node list by using the length property:
The documentElement property of the XML document is the root node.
The nodeName property of a node is the name of the node.
The nodeType property of a node is the type of the node.
You will learn more about the node properties in the next chapter of this tutorial.
The following code loops through the child nodes, that are also element nodes, of the root node:
The following code navigates the node tree using the node relationships:
Your message has been sent to W3Schools.