The insertAdjacentElement()
method inserts a given element node at a given position relative to the element it is invoked upon.
targetElement.insertAdjacentElement(position, element);
DOMString
representing the position relative to the targetElement
; must match (case-insensitively) one of the following strings: 'beforebegin'
: Before the targetElement
itself.'afterbegin'
: Just inside the targetElement
, before its first child.'beforeend'
: Just inside the targetElement
, after its last child.'afterend'
: After the targetElement
itself.The element that was inserted, or null
, if the insertion failed.
Exception | Explanation |
---|---|
SyntaxError | The position specified is not a recognised value. |
TypeError | The element specified is not a valid element. |
<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->
beforebegin
and afterend
positions work only if the node is in a tree and has an element parent.beforeBtn.addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('beforebegin',tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { 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 | Status | Comment |
---|---|---|
DOM The definition of 'insertAdjacentElement()' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 1 | 12 | 48 | Yes | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | 2.3 | 18 | 12 | 48 | Yes | Yes | Yes |
Element.insertAdjacentHTML()
Element.insertAdjacentText()
Node.insertBefore()
Node.appendChild()
(same effect as beforeend
)
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/insertAdjacentElement