Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu November 12, 2022 › #dynamically #Element

How to Insert an Element after Another Element using JavaScript

In my webpage, I have a header element with an id header and a footer element with an id footer.

Now, I want to dynamically insert a new <div> element after the header element using javascript. You can see below.

<header id="header">
  This is a header.
</header>
<!-- Here I want to insert a new div element. -->
<footer id="footer">
  This is a footer.
</footer>

To do this we can use the insertBefore() method. This method takes two parameters. The first is the new element and the second is the existing element, after which we want to inset the new element.

Syntax of the insertBefore() method. #

insertBefore(newNode,existingNode)

How to insert an element after another. #

Example : insert an element after another. #
<header id="header">
  This is a header.
</header>

<footer id="footer">
  This is a footer.
</footer>
<script>
 const myHeader = document.querySelector('#header');
 const newDiv = document.createElement('div');
       newDiv.innerText = "My new div element."
       myHeader.parentNode.insertBefore(newDiv,myHeader.nextSibling)
</script>
Try it Yourself »
  1. In the above example, we select the header element and store in a variable myHeader.
    const myHeader = document.querySelector('#header');
  2. Then, we create a new div element dynamically using the createElement() method and set its value. Know how to create a div element dynamically using Js.
    const newDiv = document.createElement('div');
          newDiv.innerText = "My new div element."
  3. Finally, using the insertBefore() method, we set the created div element after the header element.
    myHeader.parentNode.insertBefore(newDiv,myHeader.nextSibling)
Usually, insertBefore() method sets an element before another element. So, we have used the nextSibling property to insert the new element after the header element.

Conclusion #

In this article, you have learned How to Insert an Element after Another Element using JavaScript.

save
listen
AI Answer
Write Your Answer
loading
back
View All