Add an HTML Element with JavaScript insertAdjacentHTML

12/26/2021

Contents

In this article, you will learn how to add an HTML element with JavaScript insertAdjacentHTML.

What is insertAdjacentHTML?

The insertAdjacentHTML is a property that can parse the HTML or XML specified in the argument and insert the result as a node in the DOM tree.
There is innerHTML as a property that behaves similarly, but unlike innerHTML, it does not destroy existing elements when adding HTML elements.
Since the position to insert the HTML element can be easily specified by the argument, it is possible to add the HTML element at the target location.

How to use insertAdjacentHTML

The insertAdjacentHTML is described as follows:

element.insertAdjacentHTML(position, text);

position

In “position”, specify the position to insert in the specified element. The following values ​​can be specified for the argument.

beforebeginInsert just before the specified element
afterbeginInsert before the first child element in the specified element
beforeendInsert after the last child element in the specified element
afterendInsert after the specified element

text

For “text”, specify a character string that can be inserted as HTML or XML.

Add a new element

Add a new element to the HTML below.

<div id="box">
  <h1>title</h1>
</div>

beforebegin

let element = document.getElementById('box');
element.insertAdjacentHTML('beforebegin', '<p>test</p>');

//result
//<p>test</p>
//<div id="box">
//  <h1>title</h1>
//</div>

afterbegin

let element = document.getElementById('box');
element.insertAdjacentHTML('afterbegin', '<p>test</p>');

//result
//<div id="box">
//  <p>test</p>
//  <h1>title</h1>
//</div>

beforeend

let element = document.getElementById('box');
element.insertAdjacentHTML('beforeend', '<p>test</p>');

//result
//<div id="box">
//  <h1>title</h1>
//  <p>test</p>
//</div>

afterend

let element = document.getElementById('box');
element.insertAdjacentHTML('afterend', '<p>test</p>');

//result
//<div id="box">
//  <h1>title</h1>
//</div>
//<p>test</p>