JAVASCRIPT » Snippets

  Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

DOM:element.insertBefore


Summary

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

Syntax

var insertedElement = parentElement.insertBefore(newElement, referenceElement)

If referenceElement is null, newElement is inserted at the end of the list of child nodes.

  • insertedElement The node being inserted, that is newElement
  • parentElement The parent of the newly inserted node.
  • newElement The node to insert.
  • referenceElement The node before which newElement is inserted.

Example

 <html>

 <head>
 <title> DOM insertBefore test</title>
 </head>

 <body>
 <div>
   <span id="childSpan">foo bar</span>
 </div>

 <script type="text/javascript">
 // create an empty element node
 // without an ID, any attributes, or any content
 var span1 = document.createElement("span");

 // give it an id attribute called 'newSpan'
 span1.setAttribute("id", "newSpan");

 // create some content for the newly created element.
 var span1_content = document.createTextNode("This is a new span element. ");

 // apply that content to the new element
 span1.appendChild(span1_content);

 var span2 = document.getElementById("childSpan");
 var parentDiv = span2.parentNode;

 // insert the new element into the DOM before span2
 parentDiv.insertBefore(span1, span2);
 </script>

 </body>
 </html>

There is no insertAfter method, however it can be emulated using a combination of insertBefore and nextSibling.

From the above example, span1 could be inserted after span2 using:

parentDiv.insertBefore(span1, span2.nextSibling);

If span2 does not have a next sibling it must be the last child—span2.nextSibling will return null so span1 will be inserted at the end of the child nodes list (i.e. immediately after span2).


Free   Version: n/a   Platform(s): All   Updated:  August 5, 2008

Developer:EPSYLONSYS Demo Download  
Rated by: 1 user(s)  
Follow Navioo On Twitter

Submit a resource