Insert an element after another DOM element with JavaScript

In earlier articles, we looked at how to create and element and insert it before another HTML element in the DOM using vanilla JavaScript.

In this article, you'll learn different ways to insert an element after another one in the DOM with JavaScript.

The insertBefore() method, which we learned earlier to add an element before, can also be used to insert an HTML element after an HTML node. For this purpose, we need to use the element's nextSibling property that returns a reference to the next node at the same tree level.

Here is an example:

// create a new element
const elem = document.createElement('p')

// add text
elem.innerText = 'I am a software engineer.'

// grab target element reference
const target = document.querySelector('#intro')

// insert the element after target element
target.parentNode.insertBefore(elem, target.nextSibling)

The insertBefore() method works in all modern and old browsers, including Internet Explorer 6 and higher.

If you want to insert an HTML string after a certain element in the DOM, use the insertAdjacentHTML() instead, like below:

// insert HTML string after target element
target.insertAdjacentHTML('afterend', '<p>I am a software engineer.</p>')

The insertAdjacentHTML() method automatically parses the given string as HTML and inserts the resulting elements into the DOM tree at the given position. Read this guide to learn more about it.

Insert an element using after() method

ES6 introduced a new method called after() to insert an element right after an existing node in the DOM. Just call this method on the element you want to insert an element after, and pass the new element as an argument:

// insert the element after the target element

The after() method only works in modern browsers, specifically Chrome, Safari, Firefox, and Opera. At the moment, Internet Explorer doesn't support this method. However, you can use a polyfill to bring the support up to IE 9 and higher.

Read Next: How to insert an element to the DOM in JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.