Skip to main content

XML DOM Get Node Values

In the DOM, everything is a node. Element nodes do not have a text value. The text value of an element node is stored in a child node. This node is called a text node.

note

To retrieve the text value of an element, you must retrieve the value of the elements' text node.

The nodeValue property is used to get the text value of a node.

The getAttribute() method returns the value of an attribute.

Get Node Value

getElementsByTagName() method

The getElementsByTagName() method returns a node list of all elements, with the specified tag name, in the same order as they appear in the source document.

For example, this code retrieves the first <title> element:

var x = xmlDoc.getElementsByTagName("title")[0];

childNodes property

The childNodes property returns a list of an element's child nodes.

The following code retrieves the text node of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];  
y = x.childNodes[0];

nodeValue property

The nodeValue property returns the text value of a text node.

The following code retrieves the text value of the text node of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];  
y = x.childNodes[0];
z = y.nodeValue;

Get Attribute Value

In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.

The way to get the value of an attribute is to get its text value.

This can be done using the getAttribute() method or using the nodeValue property of the attribute node.

getAttribute() method

The getAttribute() method returns an attribute's value.

The following code retrieves the text value of the lang attribute of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];  
txt = x.getAttribute("lang");

getAttributeNode() method

The getAttributeNode() method returns an attribute node.

The following code retrieves the text value of the lang attribute of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];  
y = x.getAttributeNode("lang");
txt = y.nodeValue;