XML DOM Changing Node Values
The nodeValue
property is used to change the node value.
The setAttribute()
method is used to change the attribute value.
Try It Yourself - Example
The following example uses the XML file books.xml. loadXMLDoc(), located in an external JavaScript, is used to load the XML file.
Change the text node of an element
Change the attribute value using setAttribute
Change the attribute value using nodeValue
Changing the Value of an Element
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 way to change the text of an element is to change the value of this child node (the text node).
Changing the Value of a Text Node
The nodeValue
property can be used to change the value of a text node.
The following code snippet changes the text node value of the first <title>
element:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Get the text node of the first
<title>
elementChange the node value of this text node to "Easy Cooking"
Loop through and change the text node of all <title>
elements: Try it yourself
Changing the Value of an Attribute
In the DOM, attributes are also nodes. Unlike element nodes, attribute nodes have a text value.
The way to change the value of an attribute is to change its text value.
This can be done using the setAttribute()
method or the nodeValue
property of the attribute node.
Changing an Attribute Using setAttribute()
The setAttribute()
method changes the value of an existing attribute or creates a new attribute.
The following code changes the category
attribute of the <book>
element:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Get the first
<book>
elementChange the value of the "category" attribute to "food"
Loop through all <title>
elements and add a new attribute: Try it yourself
Note: If the attribute does not exist, a new attribute (with the specified name and value) is created.
Changing an Attribute Using nodeValue
The nodeValue
property can be used to change the value of an attribute node:
Example
Example explanation:
Use loadXMLDoc() to load "books.xml" into xmlDoc
Get the "category" attribute of the first
<book>
elementChange the value of this attribute node to "food"