Cloning Elements
Sometimes you need to duplicate an existing element. The cloneNode() method creates a copy of an element. Pass true to clone the element and all its children (deep clone), or false for just the element itself (shallow clone).
const original = document.querySelector("#card");
// Shallow clone — only the element, no children
const shallow = original.cloneNode(false);
// Deep clone — element plus all children
const deep = original.cloneNode(true);
document.body.appendChild(deep);
When to Use Cloning
Cloning is useful when you have a template element and want to create multiple copies of it. For example, a product card that repeats for each item in a list.
const template = document.querySelector("#productCard");
const products = [
{ name: "Laptop", price: 999 },
{ name: "Phone", price: 699 },
{ name: "Tablet", price: 499 },
];
const container = document.querySelector("#productGrid");
products.forEach(product => {
const card = template.cloneNode(true);
card.querySelector(".name").textContent = product.name;
card.querySelector(".price").textContent = `$${product.price}`;
card.style.display = "block";
container.appendChild(card);
});
Important Caveats
When you clone an element, event listeners are NOT copied. You'll need to re-attach them. Also, IDs must be unique — if you clone an element with an ID, remove or change the ID on the clone.
const clone = template.cloneNode(true);
clone.removeAttribute("id");
clone.querySelector("button").addEventListener("click", () => {
console.log("Clicked!");
});
Try it Yourself →
Template Element
HTML has a built-in <template> tag that is perfect for cloning. Content inside a template is not rendered until you clone it and add it to the DOM.
<template id="userTemplate">
<div class="user-card">
<h3 class="name"></h3>
<p class="email"></p>
</div>
</template>
const tmpl = document.querySelector("#userTemplate");
const clone = tmpl.content.cloneNode(true);
clone.querySelector(".name").textContent = "Alice";
document.body.appendChild(clone);
Summary
Cloning is a fast way to create repeated UI elements from templates. Remember that event listeners and IDs are not cloned — handle those manually.