Cloning DOM Elements
Basic clone()
The basic clone() method creates a deep copy of the selected element and its descendants, without copying any attached event handlers. The copy is a completely independent element until you insert it somewhere in the DOM.
Example: Basic clone()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Original</div>
<script>
const $copy = $("#box").clone();
$("body").append($copy);
</script>
</body>
</html>
Clone Multiple Elements
clone() can copy an entire collection of matching elements at once, not just a single one, producing a parallel set of independent copies. Each clone is separate, so modifying one afterward doesn't affect the others.
Example: Clone Multiple Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p class="item">One</p><p class="item">Two</p>
<script>
const $copies = $(".item").clone();
$("body").append($copies);
</script>
</body>
</html>
Clone with Events
Pass true to clone() to also copy any event handlers and jQuery data bound to the original element, not just its markup. Without that argument, a cloned button would look identical but wouldn't respond to clicks the same way.
Example: Clone with Events
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click", function() { console.log("Clicked"); });
const $copy = $("#btn").clone(true);
$("body").append($copy);
</script>
</body>
</html>
Clone and Modify
After cloning, you can freely change the copy's text, attributes, or classes without changing the original element at all, since the two are now entirely separate DOM nodes. This is a common way to duplicate a template element and customize each copy.
Example: Clone and Modify
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="template">Template</div>
<script>
const $copy = $("#template").clone();
$copy.text("Modified copy").attr("id", "copy1");
$("body").append($copy);
</script>
</body>
</html>
Clone Forms
Cloning can also duplicate simple form controls like inputs and selects, though care is needed since cloned inputs usually keep the same name and id as the original, which you'll want to change to avoid duplicate identifiers on the page.
Example: Clone Forms
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field1" name="field1" value="Original">
<script>
const $copy = $("#field1").clone();
$copy.attr("id", "field2").attr("name", "field2");
$("body").append($copy);
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: