Element.insertAdjacentElement()

The insertAdjacentElement() method inserts a given element node at a given position relative to the element it is invoked upon.

Syntax

JavaScript
element.insertAdjacentElement(position, element);

Parameters

position
A DOMString representing the position relative to the element; must be one of the following strings:
  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.
element
The element to be inserted into the tree.

Return value

The element that was inserted, or null, if the insertion failed.

Exceptions

Exception Explanation
SyntaxError The position specified is not a recognised value.
TypeError The element specified is not a valid element.

Visualization of position names

JavaScript
<!-- <code>beforebegin</code> -->
<code><p></code>
<!-- <code>afterbegin</code> -->
foo
<!-- <code>beforeend</code> -->
<code></p></code>
<!-- <code>afterend</code> -->
Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

Example

JavaScript
beforeBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  activeElem.insertAdjacentElement('beforebegin',tempDiv);
  setListener(tempDiv);
});

afterBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  activeElem.insertAdjacentElement('afterend',tempDiv);
  setListener(tempDiv);
});

Have a look at our insertAdjacentElement.html demo on Github (see the source code too.) Here we have a sequence of <div> elements inside a container. When one is clicked, it becomes selected and you can then press the Insert before and Insert after buttons to insert new divs before or after the selected element using insertAdjacentElement().

Specification

Specification Status Comment
DOM
The definition of 'insertAdjacentElement()' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Yes) 48.0 (48.0) ? (Yes) (Yes)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support ? 48.0 (48.0) ? ? ?

See also

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/element/insertadjacentelement

API DOM Element Gecko insertAdjacentElement Method Reference