JavaScript method: xmlDoc.insertBefore()

Inserts the specified node before a reference element as a child of the current node.

Syntax

var insertedElement = parentElement.insertBefore(newElement, referenceElement)

Arguments

The following arguments are valid for this function:

Name Data type Required Description
insertedElement XML Yes The node being inserted, that is newElement.
parentElement XML Yes The parent of the newly inserted node.
newElement XML Yes The node to insert.
referenceElement XML Yes The parent of the newly inserted node.

Usage Notes

  1. The referenceElement may NOT be null. If referenceElement is null, newElement the function will fail.
  2. The newElement must be a newly created element within the same document (created using importNode or createNode) which has not yet been attached to the tree, such as a newly created element for which appendNode has not been called. The result of invoking insertBefore using references to nodes already in the same DOM tree as newElement is undefined.

Example

var xmlDoc = new XML();
var someXML = "<doc> \
                   <one/> \
                   <two/> \
                 </doc>";
  // Create an XML document from the literal XML string  
  // we pass "false" as the second argument to setContent() to indicate
  // that the supplied string does NOT represent a path to an XML file
   
  xmlDoc.setContent( someXML, false );
  
  // Now add create and add new element <four> in one step.
  // It will be added at the end, i.e. after <two>
  
  var nodeFour = xmlDoc.addElement( "four" );
  
  // Now insert a new element <three> in front of <four>
  // We do this in two steps: 
  // a) create a new element node called <three>
  // b) insert the new element node before the <four> element
  // Note: Passing "1" as the first argument to createNode means create an element
  
  var nodeThree = xmlDoc.createNode( 1, "three" );
  
  // The newly created node has not yet been given a position in the tree.
  // Just as in the case of a node created with "importNode", we must
  // attach the new node somewhere. We can do that with appendNode or insertBefore
  // To get the new node in between two sibling nodes (as in this example)
  // we must use insertBefore. appendChild can only be used on a parent node,
  // and if we were to append to the parent element <doc>, it would end up following <four> 
  
  xmlDoc.insertBefore( nodeThree, nodeFour ); 
    
  print( xmlDoc );