XML DOM Change Node Value

nodeValue Attributes are used to change the node value.

setAttribute() The method is used to change the attribute value.

Change the value of an element

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

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

To change the text value of an element, you must change the value of the text node of the element.

Change the value of the text node

nodeValue Attributes can be used to changeThe value of the text node.

The following code changes the text node value of the first <title> element:

Example 1

xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "Chao Cai Tian Xia"

Try it yourself

Example Explanation:

  1. Assume books.xml is loaded to xmlDoc Middle
  2. Get the first child node of the <title> element
  3. Change the node value of this text node to "Chao Cai Tian Xia"

Example 2

Loop and change the text nodes of all <title> elements:

for (i = 0; i < x.length; i++) {
    x[i].childNodes[0].nodeValue = "Changed text";
}

Try it yourself

Change the value of the attribute

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

The method to change the attribute value is to change its text value.

can be used by setAttribute() Method or attribute node nodeValue to complete this task.

Use setAttribute() to change the attribute

setAttribute() MethodSet the value of an existing attribute, orCreate a new attribute.

setAttribute() The method can change the value of the attribute. If the attribute does not exist, a new attribute will be created.

This code changes the category attribute of the <book> element:

Example 1

xmlDoc.getElementsByTagName("book")[0].setAttribute("category","cooking");

Try it yourself

Example Explanation:

  1. Assume books.xml has been loaded to xmlDoc Middle
  2. Get the first <book> element
  3. Change the value of the "category" attribute to "cooking"

Example 2

Loop through all <title> elements and add new attributes:

x = xmlDoc.getElementsByTagName('title');
for (i = 0; i < x.length; i++) { 
    x[i].setAttribute("edition","First Edition");    
}

Try it yourself

Note:If the attribute does not exist, a new attribute (with the specified name and value) will be created.

Use nodeValue to change the attribute

nodeValue The attribute isThe value of the attribute node.

Change nodeValue The attribute can change the value of the attribute.

Example

xmlDoc.getElementsByTagName("book")[0].getAttributeNode("category").nodeValue = "烹饪";

Try it yourself

Example Explanation:

  1. Assume books.xml has been loaded to xmlDoc Middle
  2. Get the "category" attribute of the first <book> element
  3. Change the value of the attribute node to "cooking"