How to insert an element after another DOM element with JavaScript

published: 11 Aug 2022

2 min read

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 element in the DOM by using vanilla JavaScript.

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

The insertBefore() method, we learned earlier to add an element before, can also be used to insert an element after an HTML node. For this purpose, we need to use the element's nextSibling property that returns a reference to an immediate 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. Take a look at this guide to learn more about it.

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

Just like the before() method, after() only works in modern browsers specifically in 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

How to insert an element after another DOM element with JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming