XML DOM Changing Node Values
The nodeValue property is used to change a node's value.
The setAttribute() method is used to change an attribute's value.
Try it - Example
The following example uses the XML file books.xml.
function loadXMLDoc(), located in an external JavaScript, used to load the XML file.
Change an Element's Text Node
This example uses the nodeValue property to change the first element in "books.xml"
Change an attribute value by using setAttribute
This example uses the setAttribute() method to change the first
Change an attribute value by using nodeValue
This example uses the nodeValue property to change the first
Change the value of an element
In the DOM, every component is a node. Element nodes have no 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 an element's text is to change the value of this child node (the text node).
Change 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 first
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
element's text node
Loop through and change all
Change an Attribute's Value
In the DOM, attributes are also nodes. Unlike element nodes, attribute nodes have a text value. I
The way to change an attribute's value is to change its text value.
This can be done by using the setAttribute() method or the nodeValue property of the attribute node.
Change an Attribute Using setAttribute()
The setAttribute() method changes the value of an existing attribute, or creates a new attribute.
The following code changes
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
Element - Change the "category" attribute's value to "food"
Iterate over all the
**Note:** If the attribute does not exist, a new attribute is created (with the specified name and value).
Change an Attribute Using nodeValue
The nodeValue property can be used to change the value of an attribute node:
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0]
y=x.getAttributeNode("category");
y.nodeValue="food";
Try it »
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
element's "category" attribute - Change the attribute node's value to "food"