XML DOM Access Nodes
With the DOM, you can access every node in an XML document.
Find and Access Nodes
You can find the element you want to manipulate in several ways:
- By using the getElementsByTagName() method
- By using the parentNode, firstChild,
and lastChild properties of an element node
getElementsByTagName()
The getElementsByTagName() method can find any
XML element in the entire document.
This method ignore the document structure. If you want to find
all <book> elements in the document, the getElementsByTagName() method
will find them all, regardless of on which level the <book> elements are.
This method gives you the XML elements you need regardless of where
they are in the document!
The getElementsByTagName() method returns all elements (as a nodeList) with the
specified tag name that are descendants of the element you are on when using
this method.
The getElementsByTagName() can be used on any XML
element:
getElementsByTagName() Syntax
getElementsByTagName("tagname");
|
Example
The following example returns a nodeList of all <book> elements in the document:
xmlDoc.getElementsByTagName("book");
|
nodeList
When working with a nodeList, we usually store the list in a variable, like
this:
var x=xmlDoc.getElementsByTagName("book");
|
Now the variable x contains a list of all <book> elements in the page, and we can access
the <book> elements by
their index numbers.
Note: The index starts at 0.
You can loop through the nodeList by using the length property:
var x=xmlDoc.getElementsByTagName("book");
for (var i=0;i<x.length;i++)
{
// do something with each <book> element
}
|
You can also access a specific element by using the index number.
To access the third <p> you can write:
parentNode, firstChild, and lastChild
The five properties parentNode, firstChild,
and lastChild follow the document structure and allow short-distance travel in
the document.
Look at the following XML fragment:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
|
In the HTML code above, the <title> element is the firstChild of the <book>
element, and the <price> element is the lastChild of the <book> element.
Furthermore, the <book> element is the parentNode of the <title>,
<author>, <year>, and <price> elements.
Root Nodes
There is one special document property that allow access to the
tags:
This property returns the root node of the document and exists in
all XML and HTML documents.
|