W3docs

How to Insert an Element After Another Element in JavaScript

Read this JavaScript tutorial and learn useful information about modern approaches of inserting an element after another element using two easy methods.

Inserting an element after another element in JavaScript can be done in a few ways. Let’s look at them with examples.

To insert an element after another element, you can use the <kbd class="highlighted">insertBefore()</kbd> method. Here is the syntax:

Javascript insert an element after another element

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

Here <kbd class="highlighted">referenceNode</kbd> is the node that will come after the <kbd class="highlighted">newNode</kbd>. If the <kbd class="highlighted">referenceNode</kbd> is the last child, <kbd class="highlighted">referenceNode.nextSibling</kbd> will be null, and insertBefore() handles this by appending the new node to the end of the list:

Javascript insert an element after another element

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
    <style>
      #divId {
        color: green;
        font-size: 25px;
      }
      span {
        color: blue;
        font-size: 20px;
      }
    </style>
  </head>
  <body>
    <div id="divId">Welcome to W3docs</div>
    <script>
      function insertAfter(referenceNode, newNode) {
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
      }
      let elem = document.createElement("span");
      elem.innerHTML = "It's a Javascript book";
      let div = document.getElementById("divId");
      insertAfter(div, elem);
    </script>
  </body>
</html>

You can also use the <kbd class="highlighted">insertAdjacentElement()</kbd> method, which inserts a given element node at a specified position relative to the element it is called on:

Javascript insert an element after another element

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

Here is a working example using the afterend position:

<div id="target">Target Element</div>
<script>
  const newEl = document.createElement("span");
  newEl.textContent = "Inserted after target";
  document.getElementById("target").insertAdjacentElement("afterend", newEl);
</script>

The insertBefore() Method

The <kbd class="highlighted">Node.insertBefore()</kbd> method is used to insert a node before a reference node as a child of the parent node. If the specified node already exists in the document, <kbd class="highlighted">insertBefore()</kbd> moves it from its current position to the new one, meaning that a node cannot be in two locations of the document at the same time.