HTML DOM Element insertAdjacentElement()

Example

Insert a span element after the header:

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

More examples below.


Description

The insertAdjacentElement() method inserts a an element into a specified position.

Legal positions:

ValueDescription
afterbeginAfter the beginning of the element (first child)
afterendAfter the element
beforebeginBefore the element
beforeendBefore the end of the element (last child)

Syntax

element.insertAdjacentElement(position, element)
or
node.insertAdjacentElement(position, element)

Parameters

Parameter Description
position Required.
A position relative to the element:
afterbegin
afterend
beforebegin
beforeend
element The element to insert.


More Examples

Example

Using "afterbegin":

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

Example

Using "beforebegin":

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

Example

Using "beforeend":

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

Browser Support

element.insertAjacentElement() is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.