Node: cloneNode() method - Web APIs | MDN
Syntax
js
cloneNode()
cloneNode(deep)
Parameters
deepOptional-
If
true, then the node and its whole subtree, including text that may be in childTextnodes, is also copied.If
falseor omitted, only the node will be cloned. The subtree, including any text that the node contains, is not cloned.Note that
deephas no effect on void elements, such as the<img>and<input>elements.
Return value
The new Node cloned.
The cloned node 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.
Example
Using cloneNode()
js
const p = document.getElementById("para1");
const p2 = p.cloneNode(true);
Using cloneNode() with templates
Avoid using cloneNode() on the content of a <template> element, because if the template contains custom elements, they will not be upgraded until they are inserted into the document.
js
class MyElement extends HTMLElement {
constructor() {
super();
console.log("MyElement created");
}
}
customElements.define("my-element", MyElement);
const template = document.createElement("template");
template.innerHTML = `<my-element></my-element>`;
const clone = template.content.cloneNode(true);
// No log here; my-element is undefined in the template's document
customElements.upgrade(clone);
// Still no log; my-element is still undefined in the template's document
document.body.appendChild(clone);
// Logs "MyElement created"; my-element is now upgraded
Instead, use document.importNode() to clone the template content, so that any custom elements are upgraded using the definitions in the current document:
js
const clone = document.importNode(template.content, true);
// Logs "MyElement created"; my-element is upgraded using document's definitions
document.body.appendChild(clone);
Specifications
| Specification |
|---|
| DOM # ref-for-dom-node-clonenode① |