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
target.after(elem)

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.