Easy Tutorial
❮ Dom Nodes Navigate Met Element Hasattributes ❯

XML DOM - Replacing Nodes


The replaceChild() method replaces a specified node.

The nodeValue property replaces the text in a text node.


Try It Yourself - Examples

The following examples use the XML file books.xml. The loadXMLDoc() function, located in an external JavaScript, is used to load the XML file.

Replace an element node

Replace data in a text node


Replace an Element Node

The replaceChild() method is used to replace a node.

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

Example

xmlDoc = loadXMLDoc("books.xml");

x = xmlDoc.documentElement;

// Create new book element, title element, and text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A Notebook");

// Append the text node to the title element
newTitle.appendChild(newText);
// Append the title element to the book element
newNode.appendChild(newTitle);

y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book element with the new book element
x.replaceChild(newNode, y);

Example Explanation:


Replace Data in a Text Node

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

The replaceData() method has three parameters:

Example

Example Explanation:


Using the nodeValue Property Instead

Using the nodeValue property to replace data in a text node is easier.

The following code snippet replaces the text node value in the first <title> element with "Easy Italian":

Example

Example Explanation:

You can read more about changing node values in the Changing Nodes chapter.

❮ Dom Nodes Navigate Met Element Hasattributes ❯