Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Node.cloneNode(): copying a DOM node

Node.cloneNode() creates a separate DOM node. The subtree argument determines whether descendants are also copied.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const copy = node.cloneNode();
const deepCopy = node.cloneNode(true);

node.cloneNode() returns a new node without a parent. The default subtree = false omits descendants; true copies them recursively, including text nodes. Element attributes are copied in both cases.

The copy is not the original and does not inherit listeners registered with addEventListener(). Before inserting it into the same document, change the copied id to avoid duplicates.

Calling it directly on a ShadowRoot throws NotSupportedError. This is a browser DOM API, not an ECMAScript feature; a Node.js version does not establish its availability.

Examples

const original = document.createElement('button');
original.id = 'original';
original.textContent = 'Hello';
let calls = 0;
original.addEventListener('click', () => calls++);

const shallow = original.cloneNode();
const deep = original.cloneNode(true);
deep.id = 'copy';
deep.click();

console.log(shallow.childNodes.length);
console.log(deep.textContent);
console.log(deep.parentNode === null);
console.log(deep === original);
console.log(calls);

Result

0
Hello
true
false
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources