# Insert an element after another DOM element with JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 11, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-insert-element-after

> Learn how to create and insert an element after another element in the DOM by using vanilla JavaScript.

In earlier articles, we looked at how to [create](https://attacomsian.com/blog/javascript-create-dom-element) and element and [insert](https://attacomsian.com/blog/javascript-insert-element-before) 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:

```javascript
// 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:

```javascript
// 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](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) 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:

```javascript
// 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](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/after#polyfill) to bring the support up to IE 9 and higher.

**Read Next:** [How to insert an element to the DOM in JavaScript](https://attacomsian.com/blog/javascript-insert-element)
