Last updated on May 19, 2009
// 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.add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
How to test your PHP scripts