XML DOM replaceChild() method

Node object reference manual

Definition and usage

The replaceChild() method can replace one child node with another.

If the replacement is successful, this method can return the replaced node, and if the replacement fails, it will return NULL.

Syntax:

nodeObject.replaceChild(new_node,old_node)
Parameter Description
new_node Required. Specify the new node.
old_node Required. Specify the node to be replaced.

Tips and notes

Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following examples, we will use a function to check the node type of the first child node.

The node type of an element node is 1, so if the first child node is not an element node, it will move to the next node and continue to check whether this node is an element node. This process will continue until the first element child node is found. By this method, we can get the correct method in Internet Explorer and Mozilla.

Tip:For more information on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter

Example

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

The following code snippet can replace the <title> element of the first <book> element:

//check if first child node is an element node
function get_firstchild(n)
{
var x=n.firstChild;
while (x.nodeType!=1)
  {
  x=x.nextSibling;
  }
return x;
}
xmlDoc=loadXMLDoc("books.xml");
//create a title element and a text node
var newNode=xmlDoc.createElement("title");
var newText=xmlDoc.createTextNode("Giada's Family Dinners");
//add the text node to the title node
newNode.appendChild(newText);
//replace the first child node with the new node
var x=xmlDoc.getElementsByTagName("book")[0];
x.replaceChild(newNode,get_firstchild(x));
//output all titles
var 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

Node object reference manual