XML DOM Node Information
The nodeName, nodeValue, and nodeType properties contain information about the node.
Try It Yourself - Examples
The following examples use the XML file books.xml. loadXMLDoc(), located in an external JavaScript, is used to load the XML file.
Get the node name of an element node
Get the node name and type of an element node
Node Properties
In the XML DOM, every node is an object.
Objects have methods and properties, which can be accessed and manipulated using JavaScript.
The three important node properties are:
- nodeName
- nodeValue
- nodeType
nodeName Property
The nodeName property specifies the name of the node.
- nodeName is read-only
- The nodeName of an element node is the same as the tag name
- The nodeName of an attribute node is the attribute name
- The nodeName of a text node is always #text
- The nodeName of a document node is always #document
nodeValue Property
The nodeValue property specifies the value of the node.
- The nodeValue of an element node is undefined
- The nodeValue of a text node is the text itself
- The nodeValue of an attribute node is the attribute value
Get the Value of an Element
The following code retrieves the value of the text node of the first <title> element:
Example
xmlDoc = loadXMLDoc("books.xml");
x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt = x.nodeValue;
Result: txt = "Everyday Italian"
Example explanation:
- Use loadXMLDoc() to load "books.xml" into xmlDoc
- Get the text node of the first <title> element
- Set the txt variable to the value of the text node
Change the Value of an Element
The following code changes the value of the text node of the first <title> element:
Example
xmlDoc = loadXMLDoc("books.xml");
x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue = "Easy Cooking";
Example explanation:
- Use loadXMLDoc() to load "books.xml" into xmlDoc
- Get the text node of the first <title> element
- Change the value of the text node to "Easy Cooking"
nodeType Property
The nodeType property specifies the type of the node.
nodeType is read-only.
The most important node types are:
Node Type | NodeType |
---|---|
Element | 1 |
Attribute | 2 |
Text | 3 |
Comment | 8 |
Document | 9 |