HTML DOM Element insertAdjacentHTML() Method

Definition and Usage

insertAdjacentHTML() The method inserts HTML code into the specified position.

Valid positions:

Value Description
afterbegin After the element begins (the first child element).
afterend After the element.
beforebegin Before the element.
beforeend Before the element ends (the last child element).

Example

Example 1

Insert a new <p> element after the header element:

const h2 = document.getElementById("myH2");
let html = "<p>My new paragraph.</p>";
h2.insertAdjacentHTML("afterend", html);

Try it yourself

Example 2

Using "afterbegin":

let html = "<span style='color:red'>My span</span>"; h2.insertAdjacentHTML("afterbegin", html);

Try it yourself

Example 3

Using "beforebegin":

h2.insertAdjacentHTML("beforebegin", html);

Try it yourself

Example 4

Using "beforeend":

h2.insertAdjacentHTML("beforeend", html);

Try it yourself

Syntax

element.insertAdjacentHTML(position, html)

or

node.insertAdjacentHTML(position, html)

Parameter

Parameter Description
position

Required. The position relative to the element:

  • afterbegin
  • afterend
  • beforebegin
  • beforeend
html the HTML to be inserted.

Browser support

All browsers support element.insertAdjacentHTML():

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support