How to Insert an Element After Another Element in JavaScript

JavaScript is a popular scripting language used for developing dynamic web pages.

It allows developers to manipulate HTML elements in various ways, including inserting new elements into the DOM (Document Object Model).

When building a dynamic website, it’s common to need to insert new elements into the DOM.

This can be achieved by creating a new element, setting its attributes, and then appending it to the parent element.

However, sometimes it’s necessary to insert the element after a specific element in the DOM tree. In this case, you can use JavaScript to achieve this.

In this Javascript tutorial, we’ll look at how to insert an element after another element in JavaScript.


Code Examples

There are several ways to insert an element after another element in JavaScript.

Here are two commonly used methods:

Using insertAdjacentHTML()

The insertAdjacentHTML() method is a DOM method that allows you to insert HTML text as a string after a specific element in the DOM.

It takes two parameters: the first is the position where you want to insert the new element and the second is the HTML text of the new element.

Here’s an example that demonstrates how to use insertAdjacentHTML():

<div id="parent">
  <p>Hello World</p>
</div>

<script>
  let newElement = "<p>Inserted Element</p>";
  let parent = document.getElementById("parent");
  parent.children[0].insertAdjacentHTML("afterend", newElement);
</script>

In this example, the new element <p>Inserted Element</p> is inserted after the first child element of the parent element with an id of “parent”.

Using Node.cloneNode() and Node.insertBefore()

Another way to insert an element after another element in JavaScript is to create a new node using the Node.cloneNode() method and then insert it using the Node.insertBefore() method.

Here’s an example that demonstrates how to use Node.cloneNode() and Node.insertBefore():

<div id="parent">
  <p>Hello World</p>
</div>

<script>
  let newElement = document.createElement("p");
  newElement.innerHTML = "Inserted Element";
  let parent = document.getElementById("parent");
  parent.appendChild(newElement.cloneNode(true));
  parent.insertBefore(newElement, parent.children[1]);
</script>

In this example, a new node is created using the document.createElement() method and its innerHTML is set to “Inserted Element”.

The new node is then inserted after the first child element of the parent element with an id of “parent” using the Node.insertBefore() method.


Conclusion

Inserting an element after another element in JavaScript is a common task for developers building dynamic websites.

The two methods described in this post, insertAdjacentHTML() and Node.cloneNode() + Node.insertBefore(), are two commonly used methods for achieving this.

Choose the method that works best for your use case and keep it in mind as you build dynamic web pages.