Clone
Make a copy of elements to reuse elsewhere on the page.
Syntax
$(selector).clone();.clone() creates a deep copy of the selected elements. The copy is detached until you insert it somewhere.
var copy = $("#template").clone();
copy.appendTo("#list");This is handy for duplicating a template row or card.
Example
Loading editor…
Press Run to see the result.
When to use it
- A form builder clones a repeater row template and appends it to the fieldset when the user clicks Add Row.
- A dashboard widget system copies a card template with .clone() and populates it with different data for each metric.
- A copy-to-clipboard helper clones an input, moves it off-screen, selects its value, and removes the clone after copying.
More examples
Clone a template row and append
.clone(true) deep-copies the template element including its event handlers and appends it as a usable form row.
<div id="template" style="display:none;">
<input type="text" placeholder="Item name" />
<button class="remove-row">Remove</button>
</div>
<div id="rows"></div>
<button id="addRow">Add row</button>
<script>
$(function () {
$("#addRow").click(function () {
var $row = $("#template").clone(true).show();
$row.removeAttr("id");
$("#rows").append($row);
});
$("#rows").on("click", ".remove-row", function () {
$(this).closest("div").remove();
});
});
</script>Clone with events using clone(true)
clone(true) copies the element with its event bindings, so cloned card buttons trigger the same handler.
<div class="card" style="padding:12px;background:#eef;margin:4px;">
Card <button class="card-btn">Click me</button>
</div>
<button id="dup">Duplicate card</button>
<p id="log"></p>
<script>
$(function () {
$(".card-btn").on("click", function () {
$("#log").text("Button inside cloned card clicked!");
});
$("#dup").click(function () {
$(".card").first().clone(true).appendTo("body");
});
});
</script>Clone and detach for copy logic
Cloning each <li> before appending ensures the source list is unchanged while a separate copy populates the target.
<ul id="source">
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
</ul>
<ul id="target"></ul>
<button id="copy">Copy list</button>
<script>
$(function () {
$("#copy").click(function () {
$("#target").empty();
$("#source li").clone().appendTo("#target");
});
});
</script>
Discussion