jQuery - .clone()
In jQuery, .clone()
is used to create a copy of selected elements. The optional parameter true
makes a deep clone including events and data.
1. Basic .clone()
var copy = $('#myDiv').clone();
-
This creates a shallow clone of the element.
-
Does not copy:
-
Event handlers (
.click()
,.on()
, etc.) -
jQuery data attached with
.data()
-
2. .clone(true)
— Deep Cloning
var copyWithEvents = $('#myDiv').clone(true);
-
Copies everything, including:
-
Child elements (deep copy)
-
Event handlers bound with
.on()
or.bind()
-
jQuery data associated with the elements
-
3. Example
<div id="original">Click me</div>
// Add a click handler
$('#original').on('click', function() {
alert('Original clicked!');
});
// Shallow clone (events not copied)
var shallowClone = $('#original').clone();
$('body').append(shallowClone);
// Deep clone (events copied)
var deepClone = $('#original').clone(true);
$('body').append(deepClone);
-
Clicking shallowClone → nothing happens
-
Clicking deepClone → shows alert because the click handler is copied
Key Notes
-
.clone(true)
only clones events and data attached via jQuery, not native DOM properties likechecked
states or custom JavaScript properties. -
For nested elements,
true
ensures that child elements and their events are also cloned.