Document.importNode() - Web APIs 编辑

The Document object's importNode() method creates a copy of a Node or DocumentFragment from another document, to be inserted into the current document later.

The imported node is not yet included in the document tree. To include it, you need to call an insertion method such as appendChild() or insertBefore() with a node that is currently in the document tree.

Unlike document.adoptNode(), the original node is not removed from its original document. The imported node is a clone of the original.

Syntax

const importedNode = document.importNode(externalNode [, deep]);

Parameters

externalNode
The external Node or DocumentFragment to import into the current document.
deep Optional
A Boolean which controls whether to include the entire DOM subtree of the externalNode in the import.
  • If deep is set to true, then externalNode and all of its descendants are copied.
  • If deep is set to false, then only externalNode is imported — the new node has no children.

Note: In the DOM4 specification, deep was an optional argument with a default value of true.

This default has changed in the latest spec! The new default value is false.

Best Practice: Though it's still an optional argument, you should always provide the deep argument for backward and forward compatibility.

  • With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3), the console warns developers not to omit the argument.
  • Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone.

Return value

The copied importedNode in the scope of the importing document.

Note: importedNode's Node.parentNode is null, since it has not yet been inserted into the document tree!

Example

const iframe  = document.querySelector("iframe");
const oldNode = iframe.contentWindow.document.getElementById("myNode");
const newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);

Notes

Before they can be inserted into the current document, nodes from external documents should either be:

Best Practice: Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility.

For more on the Node.ownerDocument issues, see the W3C DOM FAQ.

Specifications

SpecificationStatusComment
DOM
The definition of 'document.importNode()' in that specification.
Living Standard
Document Object Model (DOM) Level 2 Core Specification
The definition of 'document.importNode()' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:81 次

字数:5954

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文