Node.cloneNode() - Web APIs 编辑

The Node.cloneNode() method returns a duplicate of the node on which this method was called.

Syntax

let newClone = node.cloneNode([deep])
node
The node to be cloned.
newClone

The new node, cloned from node.

The newClone has no parent and is not part of the document, until it is added to another node that is part of the document (using Node.appendChild() or a similar method). 

deep Optional*

If true, then node and its whole subtree—including text that may be in child Text nodes—is also copied.

If false, only node will be cloned. Any text that node contains is not cloned, either (since text is contained by one or more child Text nodes).

deep has no effect on empty elements (such as the <img> and <input> elements).

*Note: In the DOM4 specification (since Gecko 13.0 (Firefox 13 / Thunderbird 13 / SeaMonkey 2.10)), the optional deep argument defaults to true

This behavior has been changed in the latest spec! Although deep it still optional, it now defaults to false.

You should always provide an explicit value for backward and forward compatibility.

  • With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3)), the console warned 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.

Example

let p = document.getElementById("para1")
let p_prime = p.cloneNode(true)

Notes

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied.

Warning: cloneNode() may lead to duplicate element IDs in a document!

If the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone's ID to be unique.

Name attributes may need to be modified also, depending on whether duplicate names are expected.

To clone a node to insert into a different document, use Document.importNode() instead.

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.cloneNode()' in that specification.
Living Standard
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.cloneNode()' in that specification.
Obsolete
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Node.cloneNode()' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

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

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

发布评论

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

词条统计

浏览:133 次

字数:5426

最后编辑:7 年前

编辑次数:0 次

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