XML DOM Replace Node

The replaceChild() method replaces the specified node.

nodeValue attribute replaces the text in the text node.

Example

The following example uses an XML file books.xml.

Function loadXMLDoc(), located in external JavaScript, is used to load XML files.

Replace element nodes
In this example, replaceChild() is used to replace the first <book> node.
Replace the data in the text node
In this example, the nodeValue attribute is used to replace the data in the text node.

Replace element nodes

The replaceChild() method is used to replace nodes.

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

xmlDoc=loadXMLDoc("books.xml");
x = xmlDoc.documentElement;
//Create a book element, a title element, and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("Hello World");
//Append a text node to the title node
newTitle.appendChild(newText);
//Append a title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
//Use this new node to replace the first book node
x.replaceChild(newNode, y);

Example Explanation:

  • By using loadXMLDoc() Replace "books.xml" loaded in xmlDoc
  • Create a new element node <book>
  • Create a new element node <title>
  • Create a new text node with the text "Hello World"
  • Append this new text node to the new element node <title>
  • Append this new element node <title> to the new element node <book>
  • Replace the first <book> element node with a new <book> element node

TIY

Replace the data in the text node

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

The replaceData() method has three parameters:

  • offset - Where to start replacing characters. The offset value starts at 0.
  • length - The number of characters to replace
  • string - The string to be inserted
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"hello");

Example Explanation:

  • By using loadXMLDoc() Replace "books.xml" loaded in xmlDoc
  • Get the text node of the first <title> element
  • Use the replaceData method to replace the first 8 characters of the text node with "hello"

TIY

Use the nodeValue attribute

It is easier to replace the data in the text node using the nodeValue attribute.

The following code snippet will replace the text node value of the first <title> element with "Easy Italian":

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Hello World";

Example Explanation:

  • By using loadXMLDoc() Replace "books.xml" loaded in xmlDoc
  • Get the text node of the first <title> element
  • Use the nodeValue attribute to change the text of this text node

TIY

You can change the text of this text node using Change Node Read more about changing node values in this section.