Quick References
      ADO
      ASP
      CSS2
      HTML
      JavaScript
      Jet SQL
      VBScript
      WML
      WMLScript
      WSH
      XHTML
      XML DOM
      XSLT

Features
      Knowledge Base
      Tutorials

Partners
     ZVON.ORG
     XML
     Planet Source Code
     VisualBuilder
     Web Design
     Your HTML Source
     XML/XSLT Forums
     ASPAlliance
     Scripts
     
     Programmers Heaven
     Tek-Tips Forums
     Developer Fusion
     Code Project











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).

XML:
<names>
   <name>Alice</name>
   <name>Bert</name>
   <name>Charlie</name>
   <name>Diane</name>
   <name>Eric</name>
</names>

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

var new_node = xml_doc.createElement("name");
var new_text = xml_doc.createTextNode("Cathy");
new_node.appendChild(new_text);
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>");

Output:
Alice
Bert
Cathy
Charlie
Diane
Eric



 


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