How to Use jQuery clone() to Duplicate Elements

The jQuery clone() method provides a quick and efficient way to create a deep copy of matched DOM elements, including their child nodes, text, and attributes. This guide explains how to use clone() to duplicate elements, append them to different parts of a webpage, and optionally preserve event handlers and data using boolean parameters.

Basic Syntax

The standard syntax for the clone() method is:

$(selector).clone([withDataAndEvents], [deepWithDataAndEvents]);
  • withDataAndEvents (optional): A boolean indicating whether event handlers and data should be copied along with the element. The default value is false.
  • deepWithDataAndEvents (optional): A boolean indicating whether event handlers and data for all children of the cloned element should be copied. The default matches the value of the first argument.

Duplicating a Simple Element

By default, calling clone() creates an exact duplicate of the HTML structure, but ignores any attached JavaScript events or jQuery data. After cloning an element, you must use an insertion method like appendTo(), prependTo(), insertAfter(), or insertBefore() to place it in the DOM.

<div class="box">Original Box</div>
<button id="duplicateBtn">Duplicate Box</button>
$('#duplicateBtn').on('click', function() {
  // Clone the box and append it to the body
  $('.box').first().clone().appendTo('body');
});

Cloning Elements with Event Handlers and Data

To duplicate an element along with its attached jQuery event listeners (such as click or hover) and associated data, pass true as the first argument:

<button class="action-btn">Click Me</button>
<button id="copyBtn">Copy Button</button>
// Attach a click event to the original button
$('.action-btn').on('click', function() {
  alert('Button clicked!');
});

// Duplicate the button along with its click handler
$('#copyBtn').on('click', function() {
  $('.action-btn').clone(true).insertAfter(this);
});

If the element contains child elements with their own separate events and data, pass true for both arguments:

$('#parentContainer').clone(true, true).appendTo('#target');

Handling Duplicate ID Attributes

When an element with an id attribute is cloned, the copied element retains the same id. Because HTML requires IDs to be unique across a page, you should modify or remove the id before inserting the clone into the DOM:

let clonedItem = $('#uniqueItem').clone();

// Remove or change the ID attribute
clonedItem.attr('id', 'uniqueItem-copy');

// Insert the modified clone
clonedItem.appendTo('#container');