The insertAdjacentElement()
method of the Element
interface inserts a given element node at a given position relative to the element it is invoked upon.
The insertAdjacentElement()
method of the Element
interface inserts a given element node at a given position relative to the element it is invoked upon.
js
insertAdjacentElement(position, element)
position
A string 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. element
The element to be inserted into the tree.
The element that was inserted, or null
, if the insertion failed.
SyntaxError
DOMException
position
specified is not a recognized value.TypeError
element
specified is not a valid element.html
<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->
Note: The beforebegin
and afterend
positions work only if the node is in a tree and has an element parent.
js
beforeBtn.addEventListener("click", () => { const tempDiv = document.createElement("div"); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement("beforebegin", tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener("click", () => { const 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 |
---|
DOM Standard # dom-element-insertadjacentelement |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
insertAdjacentElement |
1 | 17 | 48 | 8 | 3 | 4.4 | 18 | 48 | 10.1 | 1 | 1.0 |
Element.insertAdjacentHTML()
Element.insertAdjacentText()
Node.insertBefore()
(similar to beforebegin
, with different arguments) Node.appendChild()
(same effect as beforeend
)
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement