1048

There's insertBefore() in JavaScript, but how can I insert an element after another element without using jQuery or another library?

Ed The ''Pro''
  • 875
  • 10
  • 22
Xah Lee
  • 16,755
  • 9
  • 37
  • 43
  • 4
    if you need the specific case of the very last child node - http://stackoverflow.com/questions/5173545/using-javascripts-insertbefore-to-insert-item-as-last-child –  May 29 '13 at 15:38
  • 5
    https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement or https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML – Alan Larimer Sep 19 '17 at 16:26
  • 4
    @AlanLarimer that's great. thanks. do you know when's insertAdjacentElement introduced? – Xah Lee Sep 21 '17 at 01:15
  • 1
    According to MDN it's supported in IE8 and Firefox 48 (2016 August 08). Follow the trail: https://bugzilla.mozilla.org/show_bug.cgi?id=811259 --> https://www.w3.org/Bugs/Public/show_bug.cgi?id=19962 (2016 March 14) – Alan Larimer Sep 22 '17 at 11:40
  • There's also the `after` function, which gained browser support around 2016, but is not supported by IE. https://developer.mozilla.org/en-US/docs/Web/API/Element/after – ThatMatthew Aug 18 '23 at 20:03

20 Answers20

1667
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

Where referenceNode is the node you want to put newNode after. If referenceNode is the last child within its parent element, that's fine, because referenceNode.nextSibling will be null and insertBefore handles that case by adding to the end of the list.

So:

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

You can test it using the following snippet:

function insertAfter(referenceNode, newNode) {
  referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var el = document.createElement("span");
el.innerHTML = "test";
var div = document.getElementById("foo");
insertAfter(div, el);
<div id="foo">Hello</div>
Sonicd300
  • 1,950
  • 1
  • 16
  • 22
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 14
    Thanks for a great answer, but isn't it confusing to flip referenceNode and newNode in the arguments list? Why not comply with the insertBefore syntax? – GijsjanB Nov 14 '13 at 16:09
  • 11
    This code snippet doesn't handle if the referenceNode is the last child, in which it should appendChild. – Brad Vogel Oct 08 '14 at 06:04
  • @BradVogel I think he explains that the case you mention is handled by insertBefore? – Pancho Nov 13 '14 at 14:05
  • 95
    According to [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore) if the element is last (and so nextSibling is null) the newNode will be appended as expected – electroCutie Nov 25 '14 at 16:07
  • 9
    referenceNode.nextElementSibling is a better option to be used – Bhumi Singhal Aug 08 '16 at 07:30
  • 11
    @BhumiSinghal: Wrong. `insertBefore()` works with text nodes. Why do you want `insertAfter()` to be different? You should create a separate pair of functions named `insertBeforeElement()` and `insertAfterElement()` for that. – 7vujy0f0hy Mar 19 '17 at 13:58
  • this function are great, but also and bad (not finished). reference node does not have any next siblings elements (example is the last child), function will not add the element, because reference does not have any more next siblings. – Donatas Navidonskis Apr 14 '17 at 06:58
  • @DonatasNavidonskis: this concern has already been addressed by doublebackslash. – do0g Feb 11 '18 at 15:21
  • Unlike `insertBefore`, this function does not accept a null `referenceNode` - I went ahead and posted a function that does, and has the opposite behavior of `insertBefore` https://stackoverflow.com/a/51437118/283851 – mindplay.dk Jul 20 '18 at 07:20
  • 2
    The fiddle doesn't work for me, here is the stackblitz for the code instead https://stackblitz.com/edit/js-rshtm2?file=index.js – EugenSunic Oct 09 '18 at 14:28
  • 1
    Simply add random stuff to workaround `"html is not defined"` @DGRFDSGN e.g: `const html='';` – Mukyuu Mar 27 '19 at 08:08
  • 1
    This answer seems outdated, `insertAdjacentElement` looks like a better candidate nowadays. Could you maybe update your post to reflect this? This answer seems to be the most up-to-date: https://stackoverflow.com/a/50066247/4621141 – flen Mar 16 '20 at 23:40
190

insertBefore() is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use insertAdjacentElement() like this:

refElem.insertAdjacentElement(position, newElem)

It lets you reference any element, and insert the to-be moved element exactly where you want. The position can be one of: 'beforebegin', 'afterbegin', 'beforeend', 'afterend') as shown here:

// refElem.insertAdjacentElement('beforebegin', myElem); 
<p id="refElem">
    // refElem.insertAdjacentElement('afterbegin', myElem);
    ... content ...
    // refElem.insertAdjacentElement('beforeend', myElem);
</p>
// refElem.insertAdjacentElement('afterend', myElem); 

Others options to consider for similar use cases are insertAdjacentHTML() and insertAdjacentText()

References:

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
Modular
  • 6,440
  • 2
  • 35
  • 38
181

Straightforward JavaScript would be the following:

Append Before:

element.parentNode.insertBefore(newElement, element);

Append After:

element.parentNode.insertBefore(newElement, element.nextSibling);

But toss some prototypes in there for ease of use:

By building the following prototypes, you will be able to call these function directly from newly created elements.

  • newElement.appendBefore(element);

  • newElement.appendAfter(element);

.appendBefore(element) Prototype

Element.prototype.appendBefore = function (element) {
  element.parentNode.insertBefore(this, element);
},false;

.appendAfter(element) Prototype

Element.prototype.appendAfter = function (element) {
  element.parentNode.insertBefore(this, element.nextSibling);
},false;

Code Snippet to see it all in action:

/* Adds Element BEFORE NeighborElement */
Element.prototype.appendBefore = function(element) {
  element.parentNode.insertBefore(this, element);
}, false;

/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function(element) {
  element.parentNode.insertBefore(this, element.nextSibling);
}, false;


/* Typical Creation and Setup A New Orphaned Element Object */
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';


/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */
NewElement.appendAfter(document.getElementById('Neighbor2'));
div {
  text-align: center;
}
#Neighborhood {
  color: brown;
}
#NewElement {
  color: green;
}
<div id="Neighborhood">
  <div id="Neighbor1">Neighbor 1</div>
  <div id="Neighbor2">Neighbor 2</div>
  <div id="Neighbor3">Neighbor 3</div>
</div>

Run it on JSFiddle

aljgom
  • 7,879
  • 3
  • 33
  • 28
Armando
  • 1,911
  • 1
  • 10
  • 4
  • 4
    The _extension_ function names are misleading. It think it should rather be called appendMeBefore and appendMeAfter. I thought it was used like the [appendChild() Method](https://www.w3schools.com/jsref/met_node_appendchild.asp), e.g. `existingElement.appendAfter(newElement);`. See what I mean at this updated [jsfiddle](https://jsfiddle.net/zwm360z2/38/). – stomtech May 25 '17 at 09:43
  • 2
    Append After works, because if element.nextSibling does not have a next sibling, nextSibling is NULL, and then it will append at the end. – Stefan Steiger Oct 11 '19 at 14:50
  • I get warnings in jslint: Expected ';' and instead saw ','. }, false; – caston Nov 24 '20 at 04:23
82

2022 Solution - Element

EDIT: As of 2021 and beyond, ChildNode has been merged into Element. I am changing this answer as such.

New documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element

This is exactly the same as ChildNode. The "before", "after" and "remove" properties are just now part of the normal element api.

// Parent 
const el = document.body;
// New Element
const newEl = document.createElement("div");

// Insert Before Element
el.before(newEl);

// Insert After Element
// Technically this would be invalid because 
// I already inserted newEl before el.
// newEl changed location and is no longer a floating element.
// You cant insert one element in two places at once.
el.after(newEl);

// Another extra feature originally added with ChildNode is the .remove() method,
// which deletes the element from the DOM
el.remove();
newEl.remove();


2019 Solution (Outdated)

I do not reccomend using this solution, but Ill keep it here for the sake of "history"

This is safer then using a polyfill-type prototype override, its just a basic function. Sure its not very pretty, but it works.

// Parent
const el = document.body;
// New Element
const newEl = document.createElement("div");

// Function You Need
function insertAfter(el0, el1) {
    el0.parentNode.insertBefore(el1, el0.nextSibling);
}

// Insert Before Element
el.insertBefore(newEl);

// Insert After Element
insertAfter(el, newEl);

// Just remember you cant use insertAfter() or .insertBefore()
// on newEl more than once.
// You cant insert one element in two places at once.

Original Solution (Bad Practice)

I do not reccomend using this solution, it was the one I initially used when posting this answer. Ill keep it here for the sake of "history"

This is just a polyfill for the .insertAfter function that doesnt exist. This prototype directly adds the function HTMLElement.insertAfter(element); to the HTMLElement Prototype:

// Parent
const el = document.body;
// New Element
const newEl = document.createElement("div");

// Custom Method
Element.prototype.insertAfter = function(new) {
    this.parentNode.insertBefore(new, this.nextSibling);
}

// Insert Before Element
el.insertBefore(newEl)

// Insert After Element
el.insertAfter(newEl);

// Just remember you cant use .insertAfter() or .insertBefore() 
// on newEl more than once.
// You cant insert one element in two places at once.
Mister SirCode
  • 1,575
  • 14
  • 31
  • 2
    About "2020 solution": `before` and `after` are both marked as "experimental" on MDN page: `Experimental. Expect behavior to change in the future.` – izogfif Dec 10 '20 at 13:02
  • 4
    @izogfif Well, Considering its just got into the living standards, that's expected. I highly doubt they will significantly change the behavior of the method to fit a new standard. If they do, I will edit the answer. The only reason that's on the MDN docs is most likely because it was recently added to the Living Standard, so its still "experimental" even though its stable and on the current release – Mister SirCode Dec 10 '20 at 15:02
  • It is working perfectly. Full support except IE. – Miorita Apr 02 '21 at 12:23
  • 1
    @Mircea If you want it to work on IE, use the polyfill suggested in my answer. (Though lets be honest here, I doubt anyone really cares for IE anymore, I personally dont support it anymore) – Mister SirCode Apr 03 '21 at 17:25
  • 10
    `before` and `after` are no longer marked as "experimental" on the MDN page: https://developer.mozilla.org/en-US/docs/Web/API/Element/before https://developer.mozilla.org/en-US/docs/Web/API/Element/after – Optimae Feb 19 '22 at 06:40
  • @MisterSirCode You talking about IE? I have a requirement in all my apps to only use Chrome, Firefox, Opera, Safari, or Brave. Nothing else, not even Samsung Internet. I have set my apps to not allow the user to enter if they are using anything other than that (mostly outdated). – Syed M. Sannan Oct 21 '22 at 21:22
  • @Stranger I dont use IE, nor do I support it, but when I first answered this question, it was still sometimes used, hence why I brought it up – Mister SirCode Nov 04 '22 at 04:36
  • @MisterSirCode Yes, I understand that. I only mentioned it for the sake of the topic, no worries. – Syed M. Sannan Nov 04 '22 at 10:48
67

insertAdjacentHTML + outerHTML

elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)

Upsides:

  • DRYer: you don't have to store the before node in a variable and use it twice. If you rename the variable, on less occurrence to modify.
  • golfs better than the insertBefore (break even if the existing node variable name is 3 chars long)

Downsides:

  • lower browser support since newer: https://caniuse.com/#feat=insert-adjacent
  • will lose properties of the element such as events because outerHTML converts the element to a string. We need it because insertAdjacentHTML adds content from strings rather than elements.
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
40

A quick Google search reveals this script

// create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
    // target is what you want it to go after. Look for this elements parent.
    var parent = targetElement.parentNode;

    // if the parents lastchild is the targetElement...
    if (parent.lastChild == targetElement) {
        // add the newElement after the target element.
        parent.appendChild(newElement);
    } else {
        // else the target has siblings, insert the new element between the target and it's next sibling.
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}
Brian Peacock
  • 1,801
  • 16
  • 24
James Long
  • 4,629
  • 1
  • 20
  • 30
  • 30
    For anyone who stumbles upon this script, I don't recommend using it. It attempts to solve problems that @karim79's native solution already solves. His script is faster and more efficient - I'd strongly recommend using that script instead of this one. – James Long Nov 11 '13 at 11:40
  • Why? It's just a couple more lines, with added conditional for last child edge case handling. Everything else is perfectly the same. – dvdchr Nov 18 '14 at 11:32
  • 10
    As a general-rule-of-thumb in JavaScript, the browser can do a task faster than anything you can write. Although the two solutions are functionally the same, my JavaScript solution needs to be read an understood by the browser before it can be used and requires an additional check each time it's executed. The solution offered by karim79 will do all this internally, saving those steps. The difference will be trivial at best, but his solution is the better one. – James Long Nov 26 '14 at 17:10
  • 3
    In other words, it's attempting to solve a problem that doesn't exist. There's nothing inherently wrong about the extra check, but I suppose it's not propagating the best understanding of these methods – 1j01 Mar 23 '15 at 02:43
  • 3
    Pretty much. I'm leaving the script here because it's the kind of thing I used to write, but the accepted answer is the better one, shows a better understanding of the methods and is faster. There's no reason use this answer instead - I'm not even sure why it still gets upvotes – James Long Mar 23 '15 at 11:58
  • 3
    If targetElement is the last element amongst it's siblings, then `targetElement.nextSibling` will return `null`. When `node.insertBefore` is called with `null` as it's second argument, then it will add the node at the end of the collection. In other words the `if(parent.lastchild == targetElement) {` branch is superfluous, because `parent.insertBefore(newElement, targetElement.nextSibling);` will deal properly with all cases, even though it may appear otherwise at first. Many have already pointed that out in other comments. – Rolf Nov 07 '16 at 11:12
  • 1
    @Rolf - yeah, that's why I don't recommend using this script and say it's better to use the accepted answer – James Long Nov 08 '16 at 09:18
24

The method node.after (doc) inserts a node after another node.

For two DOM nodes node1 and node2,

node1.after(node2) inserts node2 after node1.

This method is not available in older browsers, so usually a polyfill is needed.

golopot
  • 10,726
  • 6
  • 37
  • 51
  • This takes a bit of manual work to implement as a functioning insertAfter though, so unfortunately I dont think this would work correctly. – Mister SirCode Dec 18 '19 at 12:42
8

Or you can simply do:

referenceNode.parentNode.insertBefore( newNode, referenceNode )
referenceNode.parentNode.insertBefore( referenceNode, newNode )
Rob Porter
  • 801
  • 8
  • 23
olvlvl
  • 2,396
  • 1
  • 22
  • 22
  • I wouldn't have thought of that approach. I'd prefer to use @karim79's [more direct answer](http://stackoverflow.com/a/4793630/1151080), but good to keep in mind. – Ben J Mar 24 '16 at 08:29
  • I would no recomment this, but +1 for creativity. – Waruyama Aug 16 '21 at 14:26
6

Step 1. Prepare Elements :

var element = document.getElementById('ElementToAppendAfter');
var newElement = document.createElement('div');
var elementParent = element.parentNode;

Step 2. Append after :

elementParent.insertBefore(newElement, element.nextSibling);
Malik Khalil
  • 6,454
  • 2
  • 39
  • 33
6

This is the simplest way we can add an element after another one using vanilla javascript

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Payel Dutta
  • 742
  • 10
  • 23
  • Not really. This appends to the end or beginning, NOT after another element. – Martin James Aug 04 '20 at 17:12
  • 2
    @MartinJames It actually DOES APPEND AFTER another element. There are four possible insertPositions: beforebegin - Inserts element BEFORE the current node beforeend - Appends element to the end of current node. So element becomes the last child of current node afterbegin - Prepends element to the beginning of current node. So element becomes first child of current node afterend - Inserts element AFTER current node. So element becomes the nextSibling of current node – flash Oct 04 '20 at 01:50
4

You can actually a method called after() in newer version of Chrome, Firefox and Opera. The downside of this method is that Internet Explorer doesn't support it yet.

Example:

// You could create a simple node
var node = document.createElement('p')

// And then get the node where you want to append the created node after
var existingNode = document.getElementById('id_of_the_element')

// Finally you can append the created node to the exisitingNode
existingNode.after(node)

A simple HTML Code to test that is:

<!DOCTYPE html>
<html>
<body>
     <p id='up'>Up</p>
    <p id="down">Down</p>
  <button id="switchBtn" onclick="switch_place()">Switch place</button>
  <script>
    function switch_place(){
      var downElement = document.getElementById("down")
      var upElement = document.getElementById("up")
      downElement.after(upElement);
      document.getElementById('switchBtn').innerHTML = "Switched!"
    }
  </script>
</body>
</html>

As expected, it moves the up element after the down element

3

insertBefore() method is used like parentNode.insertBefore(). So to imitate this and make a method parentNode.insertAfter() we can write the following code.

JavaScript

Node.prototype.insertAfter = function(newNode, referenceNode) {
    return referenceNode.parentNode.insertBefore(
        newNode, referenceNode.nextSibling); // based on karim79's solution
};

// getting required handles
var refElem = document.getElementById("pTwo");
var parent = refElem.parentNode;

// creating <p>paragraph three</p>
var txt = document.createTextNode("paragraph three");
var paragraph = document.createElement("p");
paragraph.appendChild(txt);

// now we can call it the same way as insertBefore()
parent.insertAfter(paragraph, refElem);

HTML

<div id="divOne">
    <p id="pOne">paragraph one</p>
    <p id="pTwo">paragraph two</p>
</div>

Note, that extending the DOM might not be the right solution for You as stated in this article.

Hovewer, this article was written in 2010 and things might be different now. So decide on Your own.

JavaScript DOM insertAfter() method @ jsfiddle.net

Dmytro Dzyubak
  • 1,562
  • 2
  • 22
  • 35
2

Ideally insertAfter should work similar to insertBefore. The code below will perform the following:

  • If there are no children, the new Node is appended
  • If there is no reference Node, the new Node is appended
  • If there is no Node after the reference Node, the new Node is appended
  • If there the reference Node has a sibling after, then the new Node is inserted before that sibling
  • Returns the new Node

Extending Node

Node.prototype.insertAfter = function(node, referenceNode) {

    if (node)
        this.insertBefore(node, referenceNode && referenceNode.nextSibling);

    return node;
};

One common example

node.parentNode.insertAfter(newNode, node);

See the code running

// First extend
Node.prototype.insertAfter = function(node, referenceNode) {
    
    if (node)
        this.insertBefore(node, referenceNode && referenceNode.nextSibling);

    return node;
};

var referenceNode,
    newNode;

newNode = document.createElement('li')
newNode.innerText = 'First new item';
newNode.style.color = '#FF0000';

document.getElementById('no-children').insertAfter(newNode);

newNode = document.createElement('li');
newNode.innerText = 'Second new item';
newNode.style.color = '#FF0000';

document.getElementById('no-reference-node').insertAfter(newNode);

referenceNode = document.getElementById('no-sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Third new item';
newNode.style.color = '#FF0000';

referenceNode.parentNode.insertAfter(newNode, referenceNode);

referenceNode = document.getElementById('sibling-after');
newNode = document.createElement('li');
newNode.innerText = 'Fourth new item';
newNode.style.color = '#FF0000';

referenceNode.parentNode.insertAfter(newNode, referenceNode);
<h5>No children</h5>
<ul id="no-children"></ul>

<h5>No reference node</h5>
<ul id="no-reference-node">
  <li>First item</li>
</ul>

<h5>No sibling after</h5>
<ul>
  <li id="no-sibling-after">First item</li>
</ul>

<h5>Sibling after</h5>
<ul>
  <li id="sibling-after">First item</li>
  <li>Third item</li>
</ul>
Darlesson
  • 5,742
  • 2
  • 21
  • 26
2

I know this question has far too many answers already, but none of them met my exact requirements.

I wanted a function that has the exact opposite behavior of parentNode.insertBefore - that is, it must accept a null referenceNode (which the accepted answer does not) and where insertBefore would insert at the end of the children this one must insert at the start, since otherwise there'd be no way to insert at the start location with this function at all; the same reason insertBefore inserts at the end.

Since a null referenceNode requires you to locate the parent, we need to know the parent - insertBefore is a method of the parentNode, so it has access to the parent that way; our function doesn't, so we'll need to pass the parent as a parameter.

The resulting function looks like this:

function insertAfter(parentNode, newNode, referenceNode) {
  parentNode.insertBefore(
    newNode,
    referenceNode ? referenceNode.nextSibling : parentNode.firstChild
  );
}

Or (if you must, I don't recommend it) you can of course enhance the Node prototype:

if (! Node.prototype.insertAfter) {
  Node.prototype.insertAfter = function(newNode, referenceNode) {
    this.insertBefore(
      newNode,
      referenceNode ? referenceNode.nextSibling : this.firstChild
    );
  };
}
mindplay.dk
  • 7,085
  • 3
  • 44
  • 54
1

I use the following to insert options at the end of a select. By just passing null as the second argument. I'm not sure if this is an anomaly to "select" elements as I've never tried it on anything else but may help if anyone comes here looking for this. Works on IE too (amazingly). :)

            var x = document.getElementById("SELECT_LIST");
            var boption = document.createElement("option");
            boption.text = "SOME TEXT";
            boption.value = "SOME VALUE";
            x.insertBefore(boption, null);
malac usp
  • 31
  • 2
0

This code is work to insert a link item right after the last existing child to inlining a small css file

var raf, cb=function(){
    //create newnode
    var link=document.createElement('link');
    link.rel='stylesheet';link.type='text/css';link.href='css/style.css';

    //insert after the lastnode
    var nodes=document.getElementsByTagName('link'); //existing nodes
    var lastnode=document.getElementsByTagName('link')[nodes.length-1]; 
    lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
};

//check before insert
try {
    raf=requestAnimationFrame||
        mozRequestAnimationFrame||
        webkitRequestAnimationFrame||
        msRequestAnimationFrame;
}
catch(err){
    raf=false;
}

if (raf)raf(cb); else window.addEventListener('load',cb);
eQ19
  • 9,880
  • 3
  • 65
  • 77
0

You can use appendChild function to insert after an element.

Reference: http://www.w3schools.com/jsref/met_node_appendchild.asp

Doug LN
  • 132
  • 2
  • 11
0

a robust implementation of insertAfter.

// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
  function isNode(node) {
    return node instanceof Node;
  }

  if(arguments.length < 2){
    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
  }

  if(isNode(newNode)){
    if(referenceNode === null || referenceNode === undefined){
      return this.insertBefore(newNode, referenceNode);
    }

    if(isNode(referenceNode)){
      return this.insertBefore(newNode, referenceNode.nextSibling);
    }

    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
  }

  throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};
Boiethios
  • 38,438
  • 19
  • 134
  • 183
jszhou
  • 11
  • 1
0

Lets handle all the scenarios

 function insertAfter(newNode, referenceNode) {
        if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == '#text')
            referenceNode = referenceNode.nextSibling;

        if(!referenceNode)
            document.body.appendChild(newNode);
        else if(!referenceNode.nextSibling)
            document.body.appendChild(newNode);
        else            
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);            
    }
Sami
  • 8,168
  • 9
  • 66
  • 99
0
if( !Element.prototype.insertAfter ) {
    Element.prototype.insertAfter = function(item, reference) {
        if( reference.nextSibling )
            reference.parentNode.insertBefore(item, reference.nextSibling);
        else
            reference.parentNode.appendChild(item);
    };
}
yavuzkavus
  • 1,268
  • 11
  • 17