0
0
JavascriptHow-ToBeginner · 3 min read

How to Clone Element in JavaScript: Simple Guide

To clone an element in JavaScript, use the cloneNode() method on the element you want to copy. Pass true to clone the element with its children, or false to clone only the element itself.
📐

Syntax

The cloneNode() method creates a copy of the specified element.

  • element.cloneNode(deep)
  • deep: A boolean value. true clones the element and all its child nodes. false clones only the element without children.
javascript
const clone = element.cloneNode(true);
💻

Example

This example clones a <div> element with its text and appends the clone to the document body.

javascript
const original = document.createElement('div');
original.textContent = 'Hello, I am original!';
document.body.appendChild(original);

const clone = original.cloneNode(true);
clone.textContent = 'Hello, I am a clone!';
document.body.appendChild(clone);
⚠️

Common Pitfalls

One common mistake is forgetting to pass true to cloneNode() when you want to copy child elements. Without it, only the element itself is cloned, and children are lost.

Also, cloned elements are not automatically added to the page; you must append them manually.

javascript
const original = document.createElement('div');
original.innerHTML = '<p>Child</p>';

// Wrong: clones only the div, no child copied
const shallowClone = original.cloneNode(false);
console.log(shallowClone.innerHTML); // Outputs: ""

// Right: clones div and child
const deepClone = original.cloneNode(true);
console.log(deepClone.innerHTML); // Outputs: "<p>Child</p>"
Output
"" "<p>Child</p>"
📊

Quick Reference

MethodDescription
cloneNode(true)Clones element and all child nodes
cloneNode(false)Clones only the element without children
appendChild(clone)Adds the cloned element to the document

Key Takeaways

Use cloneNode(true) to copy an element with all its children.
Use cloneNode(false) to copy only the element itself without children.
Cloned elements are not added to the page automatically; append them manually.
For dynamic content, update cloned elements before adding them to the DOM.
Always check if you need a deep clone to avoid missing child elements.