Code Premix

Insert an element after another element in JavaScript

📅September 1, 2022

In this article, we will show you how to insert an element after another element in JavaScript. Here we will use only JavaScript method to insert an element. We can also do it using other libraries.

The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.

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.

Example

<html>

<head>
   <title>Insert an element after another element in JavaScript - Code Premix</title>
</head>

<body>
   <span id="refElementId">Code</span>
   <script>
      function insertAfter(referenceNode, newNode) {
         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
      }

      var el = document.createElement("span");
      el.innerHTML = "Premix";
      el.style = "margin-left: 5px";
      var div = document.getElementById("refElementId");
      insertAfter(div, el);
   </script>
</body>

</html>

In the above example, we are adding Premix span after the Code. So the output will be Code Premix.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!