METHOD:  Object::insertBefore

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

The insertBefore method is used to insert a new child node before an existing one. If no child node exists, the new child node becomes the first. All the nodes involved in the operation must be compatible; i.e. the reference 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 are inserted before the ref node in the same order, and if the node already exists, then it is first removed.

To illustrate this, the following example uses the 'names.xml' file and creates a new 'name' element and a text node with the value of 'Cathy' which is appended to it. The new 'name' element is then inserted into the document root's list of children before the third element ('Charlie'). Then a NodeList collection is created of all the 'name' elements, and the code iterates through it displaying the value of the first child of each (the text node).


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

var new_node = xml_doc.createElement("name");
var new_text = xml_doc.createTextNode("Cathy");
var root = xml_doc.documentElement;
root.insertBefore(new_node, root.childNodes.item(2));

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