The Netlobo logo - a Nevada desert landscape

Javascript DOM insertAfter function

The Javascript DOM functions do not include an insertAfter function. In this article we show you how to create your own elegant and simple insertAfter function

Published Nov 7, 2007 by lobo235
Last updated on May 19, 2009

Javascript gives you a lot of useful functions for working with the DOM but there is no function for inserting a new node after an existing node. There are ways to do it but it is not as easy as calling an insertAfter function which should exist in Javascript's DOM tool belt but doesn't. In this article we will give you an insertAfter function that is simple, elegant, and cross-browser compliant. We will also include an example at the bottom of the page so you can see the insertAfter function in action.

Here is the code for the function, you will notice that it is quite small because it makes use of existing javascript functions to do it's job. Just copy the following code into <script> tags on your site or into an external .js file that your site uses.

// This function inserts newNode after referenceNode
function insertAfter( referenceNode, newNode )
{
    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

The function is so simple that it pretty much explains itself but we will go over what the function does anyway for anyone who is interested. To understand what is going on you must first know that referenceNode is the node after which we are going to insert newNode.

  • First, the parentNode of the referenceNode is located. The parentNode is the container we are going to put newNode in so we need to know where it is.
  • Next, we call the insertBefore function to insert our newNode but instead of passing referenceNode as the second parameter we pass the sibling that follows it so that newNode ends up after referenceNode.

Now you may be telling yourself that this is not going to work when referenceNode is the last element in it's parentNode because referenceNode will not have a nextSibling. Actually, it does work because when the second parameter of insertBefore is null then the newNode is appended to the end of the parentNode.

So there you have it, a simple, easy-to-use insertAfter function. Feel free to use, modify, and reuse it wherever you want. Here is an example of the function in action: insertAfter example

10 comments for this article.

del.icio.us logo add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
Checkbox Magic - Checking, Unchecking, and Inverting with Javascript
Get URL Parameters Using Javascript
CSS background-image Tutorial