JQuery Duplicate Elements with clone()

Duplicating an element on a page starts with selecting its source. jQuery clone() returns a copy of that element and its nested markup.

I’ll show how to prepare a copied form row by resetting its values and assigning unique IDs.

TL;DR: Duplicate an Element with jQuery

Call .clone() on the selected element, then insert the copy into its destination with a method such as .appendTo(). reset copied values and IDs when the new element must be independent.

  • Use the default .clone() when markup and descendants are enough.
  • Pass true for jQuery event handlers and data on the element, and a second true to include descendants.
  • Change copied IDs before insertion and prefer delegated events for repeated controls.

What Is jQuery clone()?

The clone method belongs to jQuery’s DOM manipulation methods and returns a jQuery collection.

“Deep copy” describes the DOM subtree, including nested elements and their markup. JavaScript objects stored as jQuery data can still be shared between the source and copy.

How to Duplicate a Form Row with jQuery Step by Step

Copy one template row, clear its editable values, assign unique IDs, and place it beside the row whose Add control was clicked.

Step 1: Mark up one source row and a destination

Give the source row a class that identifies it and place it inside a stable container. Set the Add control to type=”button” so its click does not submit the form.

<div id="contacts">
  <div class="contact-row">
    <label for="contact-name">Name</label>
    <input id="contact-name" name="contact-name" value="Ada">
    <button type="button" class="add-row">Add row</button>
  </div>
</div>

Use each control’s name value to match the form processor’s expected fields. A control without a name is omitted from the browser’s submitted form data.

Step 2: Select the clicked row, clone it, and insert it

Start from the clicked button’s containing row. If the first row is the template, select it intentionally and choose a separate destination.

$("#contacts").on("click", ".add-row", function () {
  const $row = $(this).closest(".contact-row");
  const $copy = $row.clone();
  $row.after($copy);
});

The delegated .on() handler is attached to the container, and its selector filters clicks from matching Add buttons, including buttons in rows created later. The official jQuery .on() documentation describes this delegated form.

Step 3: Reset values and assign unique IDs

A clone starts from the current DOM state, so the sample value may appear in the new row. Clear the input after copying, then create a distinct ID and update its label’s for attribute. A generated counter gives each new control a unique value.

let nextContactId = 1;

$("#contacts").on("click", ".add-row", function () {
  const $row = $(this).closest(".contact-row");
  const $copy = $row.clone();
  const newId = `contact-name-${nextContactId++}`;

  $copy.find("input").val("").attr("id", newId);
  $copy.find("label").attr("for", newId);
  $row.after($copy);
});

For a subtree with several fields, assign a distinct ID to each field and update its matching label.

For rows with remove buttons, locate the relevant row and remove that row alone. Keep the last required entry from being removed if the form needs at least one row.

The detached clone can be prepared before it enters the page. Set its label text, default values, or data attributes first, then insert it once the subtree is ready. Changes to the detached copy do not alter the source row.

Step 4: Check the copy and its event behavior

I ran the reader-facing command node jquery_clone_demo.js with jQuery 4.0.0 and jsdom 31.0.1. The test compares a default clone with a clone that requests handlers and data at the root and descendants.

default clone handler calls: 0
original id: source
clone id: copy-1
copied handler calls: 1
input value: Ada
source count: 1
missing selector matches: 0
Terminal output showing jQuery clone event behavior and selector result
Default cloning leaves the direct handler off the copy. Cloning with both event flags preserves it, while the absent selector matches zero nodes.

The copy with both event flags did call the handler, and the source remained present with its input value intact.

Edge Cases When You Clone Elements

Check the relevant row before insertion, especially when your component has attached data or event handlers. The table separates cases that look similar in the markup but behave differently after cloning.

SituationWhat happensWhat to do
Direct jQuery handlerThe root option copies it when truePrefer delegation or pass true when copying is intended
Handler on a descendantRequires the second flag for descendant handlersUse .clone(true, true) only when needed
Repeated IDThe copied attribute keeps its valueRewrite IDs and their references before insertion
Textarea or select stateBrowser control state can differ from markupSet the desired value explicitly after cloning
Object stored with .data()Nested objects or arrays can remain sharedCopy mutable data separately when isolation is required

For all option details and caveats, see the official clone API reference.

Native listeners added with addEventListener() are outside jQuery’s event data handling. The new node needs its own listener setup if it relies on a native handler.

A missing selector yields an empty jQuery collection and no browser error, leaving no row to insert. The selector check in my jquery_clone_demo.js test returned 0 matches. Confirm the source exists when the handler runs.

To inspect the result in a browser, check the destination’s child count before and after the click. Then confirm that the original input remains in its row and the new input has the intended value and ID. A copy can look correct while a label still points to an older ID, so test the label interaction as well.

For a table row, append the new row to the table body rather than directly to the table element. Browsers arrange table markup using table sections, so placing a row in tbody keeps the document structure predictable. Select the specific last or clicked row before inserting after it when ordering matters.

For a card or list item, choose whether its destination replaces existing content or adds another copy. An empty target gives one clone per action, while a persistent list grows on every click. The behavior should match the user’s expectation and the page’s layout.

When an event handler changes shared application state or sends a request, decide whether it should run for both the source and copy. A copied handler can repeat that action, so test side effects with harmless local behavior before connecting a production action.

For radio buttons, checkboxes, and select menus, set each control to its intended starting state, such as clearing checked state or selecting a placeholder option.

The jQuery html() API setter replaces target contents and clears jQuery data and handlers from the old children. Use .text() when the content is plain text rather than markup.

Data values need a separate decision from handlers. jQuery can copy its data entries when the first clone flag is enabled, but an array or object stored as a data value remains the same referenced value. If both components will mutate that value independently, create a separate application-level copy and assign it to the new node.

In a table workflow, clone the body row that owns the Add button rather than the header, footer, or every row in the table. Clear the new row before insertion so the copied display does not flash with a previous entry. When that row contains a select element or textarea, set its state after cloning because the browser’s dynamic value does not always follow the markup copy.

Use the API’s second Boolean only when descendant handlers and data must travel with the node. For a row whose buttons are covered by a handler on the table body, that extra copying is unnecessary. For a self-contained widget with direct handlers on nested controls, it can preserve the widget’s behavior, but check for repeated side effects before using it.

As a getter, html() returns the contents of the first element in a matched collection. As a setter, it replaces the contents of every target in that collection. Keep that difference in mind if a selector matches several containers, because a getter does not return a separate string for each one.

For shared application data, decide whether two rows represent the same object or separate records. If each row must save independently, build its state from that row’s controls rather than storing one mutable object in jQuery data and sharing it between copies. The clone API documents that arrays and objects in data are not recursively copied.

See CodeForGeek’s JavaScript array cloning guide for data-copy approaches and array reference behavior.

A widget library may keep state outside the element’s visible markup. A cloned date picker or editor can therefore look complete while its library behavior is missing or still associated with the source. Follow that library’s documented method for creating another instance, then verify actions on each copy separately.

Also check whether a component has registered handlers on the document or another ancestor. Such handlers remain attached to their original ancestor rather than being copied with a row. The new element may still work through that ancestor if it matches the delegated selector, but direct listeners and library-managed state need their own setup.

Conclusion

Use the clone method to make a second DOM subtree, then prepare its state before insertion. See the jQuery on() guide for handling events on new controls and the jQuery each() guide for iterating over selected elements. For the method’s exact flags, check the jQuery clone API reference.

FAQ

These answers clarify common choices when making a copy of a jQuery selection.

Does jQuery clone() copy event handlers?

No. The default clone() copies the element and descendants without jQuery event handlers or data. Pass true for the element, and a second true to include descendants.

How do I duplicate a div into another div?

Select the source, call .clone(), then append the returned collection to the target, for example $(‘.source’).clone().appendTo(‘.target’).

Why should I change IDs on a cloned element?

An ID copied with the subtree can duplicate an existing document ID. Assign unique IDs and update related label and accessibility references before insertion.

Snigdha Keshariya
Snigdha Keshariya

Snigdha Keshariya covers AI concepts and tools, from AI agents, RLHF, prompting, and model architectures to coding assistants and AI productivity tools.

Articles: 111