How to Insert an Element after another Element using JavaScript

← PrevNext →

Using JavaScript insertBefore() method. Yes, you read that right. You can use the insertBefore() method in JavaScript to insert an element after another element. No library is required. This method is different from .appendChild() method. I'll show you how.

Syntax of inserBefore() Method

Let’s see the syntax first.

insertBefore(newNode, existingNode)

The method takes two parameters. The first parameter is new node or the new element. The second parameter is the existing node or the element before which the new node (element) will be placed. That’s what the method is designed for. However, I want insert the new node after the element. There's a trick.

Now let us assume, I have two <section> elements on my web page and I want to insert a <p> element (or any other element) after the first element (section). Here’s how I’ll do this.

<!DOCTYPE html>

  <section id='header'>
    this is header

  <!--Will insert a new element here (after the header).-->
  <section id='footer'>
    this is footer

let add_new_element = () => {
  let header = document.getElementById('header');
  let newEle = document.createElement('p');
  newEle.innerHTML = 'Content inside p element';
  header.parentNode.insertBefore(newEle, header.nextSibling);


Try it

So, I have a header and footer on my web page. I am creating a <p> element dynamically and then inserting the <p> after the first section or the header.

The insertBefore() method would usually insert the new <p> element before the header element. See the 2nd parameter header.nextSibling of the method. It inserts the <p> after the header section.

To do... Remove .nextSibling property and see the difference.

header.parentNode.insertBefore(newEle, header);

Thanks for reading.

← PreviousNext →