Document:adoptNode() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Document.adoptNode()节点(DOM)从另一个文档转移至调用该方法的文档中。被转移的节点及其子树将会从原始文档(如果存在的话)中移除,并且它们的 ownerDocument 会变更为当前文档。然后节点将被插入到当前文档中。

语法

js
adoptNode(externalNode)

参数

externalNode

将要从另一份文档中转移的节点。

返回值

在导入文档的作用域中复制的 importedNode

调用此方法后,importedNodeexternalNode 是同个对象。

备注: importedNodeNode.parentNodenull,因为它尚未插入文档树中!

示例

js
const iframe = document.querySelector("iframe");
const iframeImages = iframe.contentDocument.querySelectorAll("img");
const newParent = document.getElementById("images");

iframeImages.forEach((imgEl) => {
  newParent.appendChild(document.adoptNode(imgEl));
});

备注

在将来自外部文档的节点插入到当前文档之前,应该先进行以下操作之一:

有关 Node.ownerDocument 问题的更多信息,请参阅 W3C DOM 常见问题

规范

Specification
DOM
# ref-for-dom-document-adoptnode①

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
adoptNode

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见