Skip to main content

XML DOM Set Node Values

The nodeValue property is used to change a node value and The setAttribute() method is used to change an attribute value.

Consider node.nodeValue;:

  • If node is an Attribute then the value variable will be the value of the attribute.
  • If node is a Text node it will be the text content.
  • If node is an Element it will be null.

Change the Value of an Element

note

In the DOM, everything is a node. Element nodes do not have a text value.

Change the Value of a Text Node

The text value of an element node is stored in a child node. This node is called a text node.

The nodeValue property can be used to change the value of a text node.

For example: change the text node value of the first <title> element:

xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue  =  "My New Title "

Change the Value of an Attribute Node

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

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

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

Change an Attribute Using setAttribute()

The setAttribute() method changes the value of an attribute.

If the attribute does not exist, a new attribute is created.

For example: change publisher attribute of the <book> element:

xmlDoc.getElementsByTagName("book")[0].setAttribute("publisher","Tutorial Reference");
note

If the attribute does not exist, a new attribute is created using the specified name and value.

Change an Attribute Using nodeValue

The nodeValue property is the value of a attribute node.

Changing the value property changes the value of the attribute.

For example: change publisher attribute of the <book> element:

xmlDoc.getElementsByTagName("book")[0].getAttributeNode("publisher").nodeValue = "Tutorial Reference";