XML DOM Replacing Nodes

replaceChild() The method replaces the specified node.

nodeValue Properties replace the text in the text node.

Replace element nodes

replaceChild() The method is used to replace nodes.

The following code snippet replaces the first <book> element:

Example

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
// Create a book element, title element, and text node
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A New Book");
// Add the text node to the title node
newTitle.appendChild(newText);
// Add this title node to the book node
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0];
// Replace the first book node with the new node
x.replaceChild(newNode,y);

x.nodeValue="A new book";

Try it yourself

  1. The example explains: books.xml loaded to xmlDoc in
  2. Create a new element node <book>
  3. Create a new element node <title>
  4. Create a new text node containing the text "A New Book"
  5. Append this new text node to the new element node <title>
  6. Append this new element node <title> to the new element node <book>
  7. Replace the first <book> element node with a new <book> element node

Replace the data in the text node

replaceData() The method is used to replace the data in the text node.

replaceData() The method has three parameters:

  • offset - Where to start replacing characters. The offset starts from zero
  • length - The number of characters to replace
  • string - The string to be inserted

Example

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,4,"A New Book");

x.nodeValue="A new book";

Try it yourself

  1. The example explains: books.xml loaded to xmlDoc in
  2. Get the text node of the first <title> element node
  3. Use replaceData() The method replaces the first eight characters of the text node with "A New Book"

Use the nodeValue property instead

Use nodeValue Properties are easier to replace the data in the text node.

The following code snippet replaces the text node value of the first <title> element with "A New Book":

Example

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="一本新书";

x.nodeValue="A new book";

Try it yourself

  1. The example explains: books.xml loaded to xmlDoc in
  2. Get the text node of the first <title> element node
  3. Use nodeValue Use attributes to change the text of a text node

You can read more about changing node values in the 'Change Node' chapter.