insert element after another element in js

How to Insert Element After Another Element in JavaScript

JavaScript provides InsertBefore() function to insert an element before another element. But it does not provide a built in function to insert element after another element. Nevertheless this is a common requirement for web developers and many third party libraries like jQuery provide functions for such things. In this article, we will learn how to insert element after another element in JavaScript.

How to Insert Element After Another Element in JavaScript

Let us say you have a div element as shown below.

<div id="hello">Hello</div>

Let us say you want to add the following div after the above div.

var el = document.createElement("div");
el.innerHTML = "test";

JavaScript provides insertBefore() function that takes two arguments – new node to be inserted, and the reference node before which you want to insert new node.

insertBefore(newNode, referenceNode)

We will use this to create a JavaScript function insertAfter() for this purpose.

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

In the above code, referenceNode is the element before which we want to add the new element. We use the insertBefore() function, but we call it on referenceNode.nextsibling which is the element after referenceNode. If our referenceNode is the last element, that is fine, since referenceNode.nextsibling will be null and the new element will be added as the last element.

Once we have defined the above function, we can easily call it as shown below.

var div = document.getElementById("hello");
insertAfter(div, el);

To summarize,

Append Before:

element.parentNode.insertBefore(newElement, element);

Append After:

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

If you want, you can create a prototype for insertAfter so that you can directly call it on any DOM element.

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

Now you can use this as


In this article, we have learnt several ways to insert element after another element in JavaScript, without using any third-party library. You can customize them as per your requirement. This is a useful function or prototype to have in every website and application, since we frequently need to insert DOM elements on our web page. So it is advisable to define this prototype in a JS file and import it on all your web pages where you need to insert element. This will make it easy for you to call the prototype from any part of your website or application.

Also read:

How to Sum Values of JS Object
How to Access POST Form Fields in ExpressJS
How to Detect Scroll Direction in JavaScript
How to Split String With Multiple Delimiters in JS
How to Split String With Multiple Delimiters in Python

Leave a Reply

Your email address will not be published.