[javascript] How to insert an element after another element in JavaScript without using a library?

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

This question is related to javascript dom insert append

The answer is


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:

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

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


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);
    }
}

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'."));
};

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);            
    }

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


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);

2018 Solution (Bad Practice, go to 2020)

I know this question is Ancient, but for any future users, heres a modified prototype this is just a micro polyfill for the .insertAfter function that doesnt exist this prototype directly adds a new function baseElement.insertAfter(element); to the Element prototype:

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

Once youve placed the polyfill in a library, gist, or just in your code (or anywhere else where it can be referenced) Just write document.getElementById('foo').insertAfter(document.createElement('bar'));


2019 Solution (Ugly, go to 2020)

You SHOULD NOT USE PROTOTYPES. They overwrite the default codebase and arent very efficient or safe and can cause compatibility errors, but if its for non-commercial projects, it shouldnt matter. if you want a safe function for commercial use, just use a default function. its not pretty but it works:

function insertAfter(el, newEl) {
    el.parentNode.insertBefore(newEl, this.nextSibling);
}

// use

const el = document.body || document.querySelector("body");
// the || means "this OR that"

el.insertBefore(document.createElement("div"), el.nextSibling);
// Insert Before

insertAfter(el, document.createElement("div"));
// Insert After 

2020 Solution

Current Web Standards for ChildNode: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode

Its currently in the Living Standards and is SAFE.

For Unsupported Browsers, use this Polyfill: https://github.com/seznam/JAK/blob/master/lib/polyfills/childNode.js

Someone mentioned that the Polyfill uses Protos, when I said they were bad practice. They are, especially when they are used blindly and overwrited, like with my 2018 solution. However, that polyfill is on the MDN Documentation and uses a kind of initialization and execution that is safer.

How to use the 2020 Solution:

// Parent Element
const el = document.querySelector(".class");

// Create New Element
const newEl = document.createElement("div");
newEl.id = "foo";

// Insert New Element BEFORE an Element
el.before(newEl);

// Insert New Element AFTER an Element
el.after(newEl);

// Remove an Element
el.remove();

// Even though it’s a created element,
// newEl is still a reference to the HTML,
// so using .remove() on it should work
// if you have already appended it somewhere
newEl.remove();

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.


if( !Element.prototype.insertAfter ) {
    Element.prototype.insertAfter = function(item, reference) {
        if( reference.nextSibling )
            reference.parentNode.insertBefore(item, reference.nextSibling);
        else
            reference.parentNode.appendChild(item);
    };
}

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

insertAdjacentElement() (see MDN) This lets you reference any element, and insert the to-be moved element exactly where you want:

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

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

References:

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


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.

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

_x000D_
_x000D_
// First extend_x000D_
Node.prototype.insertAfter = function(node, referenceNode) {_x000D_
    _x000D_
    if (node)_x000D_
        this.insertBefore(node, referenceNode && referenceNode.nextSibling);_x000D_
_x000D_
    return node;_x000D_
};_x000D_
_x000D_
var referenceNode,_x000D_
    newNode;_x000D_
_x000D_
newNode = document.createElement('li')_x000D_
newNode.innerText = 'First new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-children').insertAfter(newNode);_x000D_
_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Second new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-reference-node').insertAfter(newNode);_x000D_
_x000D_
referenceNode = document.getElementById('no-sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Third new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);_x000D_
_x000D_
referenceNode = document.getElementById('sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Fourth new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);
_x000D_
<h5>No children</h5>_x000D_
<ul id="no-children"></ul>_x000D_
_x000D_
<h5>No reference node</h5>_x000D_
<ul id="no-reference-node">_x000D_
  <li>First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>No sibling after</h5>_x000D_
<ul>_x000D_
  <li id="no-sibling-after">First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>Sibling after</h5>_x000D_
<ul>_x000D_
  <li id="sibling-after">First item</li>_x000D_
  <li>Third item</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


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


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;

And, To See It All In Action, Run the Following Code Snippet

_x000D_
_x000D_
/* Adds Element BEFORE NeighborElement */_x000D_
Element.prototype.appendBefore = function(element) {_x000D_
  element.parentNode.insertBefore(this, element);_x000D_
}, false;_x000D_
_x000D_
/* Adds Element AFTER NeighborElement */_x000D_
Element.prototype.appendAfter = function(element) {_x000D_
  element.parentNode.insertBefore(this, element.nextSibling);_x000D_
}, false;_x000D_
_x000D_
_x000D_
/* Typical Creation and Setup A New Orphaned Element Object */_x000D_
var NewElement = document.createElement('div');_x000D_
NewElement.innerHTML = 'New Element';_x000D_
NewElement.id = 'NewElement';_x000D_
_x000D_
_x000D_
/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */_x000D_
NewElement.appendAfter(document.getElementById('Neighbor2'));
_x000D_
div {_x000D_
  text-align: center;_x000D_
}_x000D_
#Neighborhood {_x000D_
  color: brown;_x000D_
}_x000D_
#NewElement {_x000D_
  color: green;_x000D_
}
_x000D_
<div id="Neighborhood">_x000D_
  <div id="Neighbor1">Neighbor 1</div>_x000D_
  <div id="Neighbor2">Neighbor 2</div>_x000D_
  <div id="Neighbor3">Neighbor 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Run it on JSFiddle


You can use appendChild function to insert after an element.

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


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
    );
  };
}

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);

Or you can simply do:

referenceNode.parentNode.insertBefore( newNode, referenceNode )
referenceNode.parentNode.insertBefore( referenceNode, newNode )

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to insert

How to insert current datetime in postgresql insert query How to add element in Python to the end of list using list.insert? Python pandas insert list into a cell Field 'id' doesn't have a default value? Insert a row to pandas dataframe Insert at first position of a list in Python How can INSERT INTO a table 300 times within a loop in SQL? How to refresh or show immediately in datagridview after inserting? Insert node at a certain position in a linked list C++ select from one table, insert into another table oracle sql query

Examples related to append

List append() in for loop ValueError: all the input arrays must have same number of dimensions Append a tuple to a list - what's the difference between two ways? How merge two objects array in angularjs? How to add an element at the end of an array? Appending a list or series to a pandas DataFrame as a row? Can someone explain how to append an element to an array in C programming? How to append elements at the end of ArrayList in Java? Append value to empty vector in R? How to append new data onto a new line