XML DOM Node Information


The nodeName, nodeValue, and nodeType properties contain information about nodes.


实例

Try it Yourself - Example

The following example uses an XML filebooks.xml。
FunctionloadXMLDoc(), located in the external JavaScript, used to load the XML file.

Get the node name of an element node
This example uses the nodeName attribute to get the node name of the root element in "books.xml".

Get text from a text node
This example uses the nodeValue property to get the text of the first <title> element in "books.xml".

Change Text in a Text Node
This example uses the nodeValue property to change the text of the first <title> element in "books.xml".

Get the node name and type of an element node
This example uses the nodeName and nodeType attributes to get the node name and type of the root element in "books.xml".


Node attributes

In the XML DOM, every node is aObject。

an object with methods and properties, and can be accessed and manipulated through JavaScript.

The three important node attributes are:

  • nodeName
  • nodeValue
  • nodeType

nodeName attribute

The nodeName attribute 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 name of the attribute.
  • The nodeName of a text node is always #text.
  • The nodeName of a document node is always #document.

Try it.


nodeValue property

The nodeValue attribute 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 value of the attribute.

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;

Try it Yourself »

Result: txt = "Everyday Italian"

Example explanation:

  1. UsageloadXMLDoc()put "books.xml" Load into xmlDoc
  2. Get the text node of the first <title> element node.
  3. 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";

Try it Yourself »

Example explanation:

  1. UsageloadXMLDoc()put "books.xml" Load into xmlDoc
  2. Get the text node of the first <title> element node.
  3. Change the value of the text node to "Easy Cooking".

nodeType attribute

The nodeType attribute specifies the type of the node.

nodeType is read-only.

The most important node types are:

Node Type NodeType
element 1
Property 2
Text 3
Comments 8
Documentation 9

Try it.


other extensions