HTML DOM Element insertAdjacentElement() Method

Definition and Usage

insertAdjacentElement() The method inserts the element at the specified position.

Valid positions:

Value Description
afterbegin After the element starts (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 span element after the title:

const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("afterend", span);

Try it yourself

Example 2

Using "afterbegin":

const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("afterbegin", span);

Try it yourself

Example 3

Using "beforebegin":

const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("beforebegin", span);

Try it yourself

Example 4

Using "beforeend":

const span = document.getElementById("mySpan");
const h2 = document.getElementById("myH2");
h2.insertAdjacentElement("beforeend", span);

Try it yourself

Syntax

element.insertAdjacentElement(position, element)

or

node.insertAdjacentElement(position, element)

Parameter

Parameter Description
position

Required. The position relative to the element:

  • afterbegin
  • afterend
  • beforebegin
  • beforeend
element The element to be inserted.

Browser support

All browsers support element.insertAdjacentElement():

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