.clone( [withDataAndEvents ] )Returns: jQuery
Description: Create a deep copy of the set of matched elements.
-
version added: 1.0.clone( [withDataAndEvents ] )
-
withDataAndEvents (default:
false
)Type: BooleanA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.
-
-
version added: 1.5.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
-
withDataAndEvents (default:
false
)Type: BooleanA Boolean indicating whether event handlers and data should be copied along with the elements. The default value isfalse
. *In jQuery 1.5.0 the default value was incorrectlytrue
; it was changed back tofalse
in 1.5.1 and up. -
deepWithDataAndEvents (default:
value of withDataAndEvents
)Type: BooleanA Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults tofalse
).
-
.clone()
method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
textarea
and user selections made to a select
) is not copied to the cloned elements. When cloning input
elements, the dynamic state of the element (e.g., user data typed into text inputs and user selections made to a checkbox) is retained in the cloned elements.
.clone()
is a convenient way to duplicate elements on a page. Consider the following HTML:
1
2
3
4
|
|
.append()
, normally when an element is inserted somewhere in the DOM, it is moved from its old location. So, given the code:
1
|
|
1
2
3
4
5
6
|
|
1
|
|
1
2
3
4
5
6
7
|
|
.clone()
method, you can modify the cloned elements or their contents before (re-)inserting them into the document.
withDataAndEvents
parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the .data()
method) is also copied to the new copy.
1
2
3
4
5
|
|
withDataAndEvents
can be optionally enhanced with deepWithDataAndEvents
to copy the events and data for all children of the cloned element.
.clone()
has the side-effect of producing elements with duplicate id
attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class
attributes as identifiers instead.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|