METHOD:  Object::replaceChild

Object  Attr   CDATASection   CharacterData   Comment   Document   DocumentFragment   DocumentType   Entity   EntityReference   Node   Notation   ProcessingInstruction   Text
Object.replaceChild(newChild, oldChild)

The replaceChild method is used to replace one of a node's children with another. It returns the old child. All the nodes involved in the operation must be compatible; i.e. the old node must be a child node of this node, and the new node must be writeable and of a type that can be a child node to it (see the list of Node Types). If the new child node is a DocumentFragment all its children replace the old node in the same order, and if the node already exists, then it is first removed.

To illustrate this we shall use the 'names.xml' file and swap the second 'name' element (Bert) with the last (Eric). We first remove the latter and assign it to the variable new_node. We then use the replaceChild method to replace the former with new_node, assigning the returned old node to old_node. Finally old_node is appended to the end of the child node list and the values of the firstChild of each (the text node) are displayed in rearranged order.


Code (JavaScript):
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;

var root = xml_doc.documentElement;
var new_node = root.removeChild(root.lastChild);
var old_node = root.replaceChild(new_node, root.childNodes.item(1));

var names = xml_doc.getElementsByTagName("name");
var i, n_names = names.length;
for (i = 0; i < n_names; i++)
   document.write(names[i].firstChild.nodeValue + "<br>");


Copyright 1999-2001 by Infinite Software Solutions, Inc. All rights reserved.
Trademark Information