.clone()

.clone( [ withDataAndEvents ] ) Returns: jQuery

Description: Create a copy of the set of matched elements.

  • version added: 1.0.clone( [ withDataAndEvents ] )

    withDataAndEventsA Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4 element data will be copied as well.

The .clone() method, when used in conjunction with one of the insertion methods, is a convenient way to duplicate elements on a page. Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

As shown in the discussion for .append(), normally when we insert an element somewhere in the DOM, it is moved from its old location. So, given the code:

$('.hello').appendTo('.goodbye');

The resulting DOM structure would be:

<div class="container">
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

To prevent this and instead create a copy of the element, we could write the following:

$('.hello').clone().appendTo('.goodbye');

This would produce:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

Note that when using the .clone() method, we can modify the cloned elements or their contents before (re-)inserting them into the document.

Normally, any event handlers bound to the original element are not copied to the clone. The optional 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.

Example:

Clones all b elements (and selects the clones) and prepends them to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<b>Hello</b><p>, how are you?</p>
<script>$("b").clone().prependTo("p");</script>
</body>
</html>

Demo:

Result:

<b>Hello</b><p><b>Hello</b>, how are you?</p>