XML DOM - Retrieving Node Values
The nodeValue
property is used to get the text value of a node.
The getAttribute()
method returns the value of an attribute.
Retrieving Element Values
In the DOM, everything is a node. Element nodes do not have a text value.
The text of an element node is stored in a child node. This node is called a text node.
The method to retrieve the text of an element is to get the value of this child node (text node).
Retrieving Element Values
The getElementsByTagName()
method returns a node list of all elements with a specified tag name, in the order they appear in the source document.
The following code loads the books.xml into xmlDoc
using loadXMLDoc() and retrieves the first <title>
element:
The childNodes
property returns a list of child nodes. The <title>
element has only one child node. It is a text node.
The following code retrieves the text node of the <title>
element:
The nodeValue
property returns the text value of the text node:
Example
Result: txt = "Everyday Italian"
Traverse all <title>
elements: Try it yourself
Retrieving Attribute Values
In the DOM, attributes are also nodes. Unlike element nodes, attribute nodes have a text value.
The method to retrieve the value of an attribute is to get its text value.
This can be done using the getAttribute()
method or the nodeValue
property of the attribute node.
Retrieving Attribute Values - getAttribute()
The getAttribute()
method returns the value of an attribute.
The following code retrieves the text value of the "lang" attribute of the first <title>
element:
Example
Result: txt = "en"
Example explanation:
- Use loadXMLDoc() to load "books.xml" into
xmlDoc
- Set the
txt
variable to the value of the "lang" attribute of the first<title>
element node
Traverse all <book>
elements and get their "category" attributes: Try it yourself
Retrieving Attribute Values - getAttributeNode()
The getAttributeNode()
method returns the attribute node.
The following code retrieves the text value of the "lang" attribute of the first <title>
element:
Example
Result: txt = "en"
Example explanation:
- Use loadXMLDoc() to load "books.xml" into
xmlDoc
- Get the "lang" attribute node of the first
<title>
element node - Set the
txt
variable to the value of the attribute
Traverse all <book>
elements and get their "category" attributes: Try it yourself