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.
Definition and Usage
The insertAdjacentElement()
method inserts a an element into a specified position.
Legal positions:
Value | Description |
---|---|
afterbegin | After the beginning of the element (first child) |
afterend | After the element |
beforebegin | Before the element |
beforeend | Before 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 | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |