Element.insertAdjacentElement() - Web APIs 编辑
The insertAdjacentElement()
method of the Element
interface inserts a given element node at a given position relative to the element it is invoked upon.
Syntax
targetElement.insertAdjacentElement(position, element);
Parameters
position
- A
DOMString
representing the position relative to thetargetElement
; must match (case-insensitively) one of the following strings:'beforebegin'
: Before thetargetElement
itself.'afterbegin'
: Just inside thetargetElement
, before its first child.'beforeend'
: Just inside thetargetElement
, after its last child.'afterend'
: After thetargetElement
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
<!--Note: Thebeforebegin
--><p>
<!--afterbegin
--> foo <!--beforeend
--></p>
<!--afterend
-->
beforebegin
and afterend
positions work only if the node is in a tree and has an element parent.Example
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()
.
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'insertAdjacentElement()' in that specification. | Living Standard |
Browser compatibility
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
See also
Element.insertAdjacentHTML()
Element.insertAdjacentText()
Node.insertBefore()
(similar tobeforebegin
, with different arguments)Node.appendChild()
(same effect asbeforeend
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论