Insert an element or HTML block before or after an existing element

Reading Time: 2 minutes 🕑

Last updated: September 27, 2022.

To insert an element just before or after one that already exists in the DOM, you can call the insertAdjacentElement() method on an existing element.

This method take two arguments:

  1. Position to insert the new element relative to the existing one (in these examples beforebegin and afterend)
  2. The element to be inserted

There is also a related method, insertAdjacentHTML(), which writes HTML to the DOM rather than inserting a new element. Apart from accepting HTML instead on an element, it works in the same way as insertAdjacentElement().

Examples

Inserting before an element

To insert a new <div> element before div3, insertAdjacentElement() is called on div3, with beforebegin and newDiv as arguments:

<div id="div1">Div1</div>
<div id="div2">Div2</div>
<div id="div3">Div3</div>
<div id="div4">Div4</div>
<div id="div5">Div5</div>

<script>

// Select div3
const div3 = document.getElementById('div3');

// Create new element newDiv
const newDiv = document.createElement('div');
newDiv.id = 'new-div';
newDiv.textContent = "NewDiv";

// Insert newDiv before div3
div3.insertAdjacentElement('beforebegin', newDiv);

</script>

And below an entire block of HTML created using a template string in inserted before div3:

<div id="div1">Div1</div>
<div id="div2">Div2</div>
<div id="div3">Div3</div>
<div id="div4">Div4</div>
<div id="div5">Div5</div>

<script>

// Select div3
const div3 = document.getElementById('div3');

// Create a template string
const markup = `
<article>
  <h2>Template strings are cool</h2>
  <p>This string is going to be rendered as HTML in the DOM!</p>
</article>
`
// Insert markup before div3
div3.insertAdjacentHTML('beforebegin', markup);

</script>

Inserting after an element

To insert an element after div3, all you need to do is specify afterend instead of beforebegin when calling insertAdjacentElement():

<div id="div1">Div1</div>
<div id="div2">Div2</div>
<div id="div3">Div3</div>
<div id="div4">Div4</div>
<div id="div5">Div5</div>

<script>

// Select div3
const div3 = document.getElementById('div3');

// Create new element newDiv
const newDiv = document.createElement('div');
newDiv.id = 'new-div';
newDiv.textContent = "NewDiv";

// Insert newDiv after div3
div3.insertAdjacentElement('afterend', newDiv);

</script>

And to insert a block of HTML after div3, make the same adjustment:

<div id="div1">Div1</div>
<div id="div2">Div2</div>
<div id="div3">Div3</div>
<div id="div4">Div4</div>
<div id="div5">Div5</div>

<script>

// Select div3
const div3 = document.getElementById('div3');

// Create a template string
const markup = `
<article>
  <h2>Template strings are cool</h2>
  <p>This string is going to be rendered as HTML in the DOM!</p>
</article>
`
// Insert new markup after div3
div3.insertAdjacentElement('afterend', markup);

</script>