JavaScript Reference ยท DOM: Document and Elements
Node.cloneNode()
Reference for cloneNode(): copy an element with or without its descendants, what is and is not copied (attributes, ids, listeners), and typical uses.
cloneNode() returns a copy of a node. With cloneNode(true) the copy includes all descendants (a deep clone); with cloneNode(false), or no argument, it copies only the node itself (a shallow clone), without children.
The copy is not attached to the document. You insert it where you want it, for example with append().
const card = template.cloneNode(true); list.append(card);
Try it
Syntax
node.cloneNode() node.cloneNode(deep)
| Name | Description |
|---|---|
deep |
Optional boolean, false by default. If true, the whole subtree is copied; otherwise only the node itself. |
Return value: the new node, with no parent.
Exceptions: a NotSupportedError DOMException for node types that cannot be cloned (rare in practice).
Usage notes
- What is copied. The node type, its attributes (including
id,class,styleanddata-*), and, for a deep clone, all descendants including text nodes. For a text node the text is copied. - Duplicate ids. The copy keeps the same
id, which makes ids non-unique once you insert it. Change or remove the id (and fixfor/aria-*references) before inserting. - Listeners added with
addEventListener()are not copied. Handlers written as attributes (onclick="...") are attributes, so they are copied. Attach listeners to the clone, or use delegation on a parent. - Shallow clones lose text. The text of an element lives in child text nodes, so
cloneNode(false)of a paragraph is an empty paragraph. - JavaScript properties are not copied. Expando properties you set on the element (
el.myData = 1) stay on the original. Usedata-*attributes if the data must survive cloning. - Form state. Attributes are copied, and current values of inputs are generally carried over too, but the details vary by control, so test checkboxes, selects and textareas if you rely on it.
- Other documents. To copy a node from another document into this one, use
document.importNode(node, true). - Templates. A
<template>'s contents live in itscontentfragment:template.content.cloneNode(true)gives an independent copy. See the template element. - Plain objects.
cloneNode()is only for DOM nodes. For data, usestructuredClone().
Browser support
Supported in every browser. Behavior of the optional argument has been consistent for many years, though very old code always passes true or false explicitly.