XML DOM replaceChild() Method

Definition and Usage

The replaceChild() method replaces a child node with another node.

If successful, this method returns the replaced node, or null if it fails.

Syntax:

elementNode.replaceChild(new_node,old_node)
Parameter Description
new_node Required. Specifies the new node.
old_node Required. Specifies the child node to be replaced.

Example

In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().

The following code snippet replaces the first <title> element of the first <book> element in "books.xml":

//check if first child node is an element node
function get_firstchild(n)
{
x=n.firstChild;
while (x.nodeType!=1)
  {
  x=x.nextSibling;
  }
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
//create a title element and a text node
newNode=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("Giada's Family Dinners");
//add the text node to the title node,
newNode.appendChild(newText);
//replace the last node with the new node
x.replaceChild(newNode,get_firstchild(x));
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}

Output:

Giada's Family Dinners
Harry Potter
XQuery Kick Start
Learning XML

Note:Internet Explorer will ignore the blank text nodes generated between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the above example, we created a function to create the correct child elements.

Tip:For more information about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com DOM browser This section.