jQuery API

.clone()

.clone( [withDataAndEvents] ) Returns: jQuery

Description: Create a deep 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.

  • version added: 1.5.clone( [withDataAndEvents] [, deepWithDataAndEvents] )

    withDataAndEventsA Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.

    deepWithDataAndEventsA 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 to false).

The .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. When used in conjunction with one of the insertion methods, .clone() 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 an element is inserted 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, you 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: When using the .clone() method, you 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.

However, objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, copy each one manually:

var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data
    $clone = $elem.clone( true )
    .data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing

As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

Note: Using .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.

Examples:

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:

Example: When using .clone() to clone a collection of elements that are not attached to the DOM, their order when inserted into the DOM is not guaranteed. However, it may be possible to preserve sort order with a workaround, as demonstrated:

<!DOCTYPE html>
<html>
<head>
  <style>
  #orig, #copy, #copy-correct {
    float: left;
    width: 20%;
  }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div id="orig">
    <div class="elem"><a>1</a></div>
    <div class="elem"><a>2</a></div>
    <div class="elem"><a>3</a></div>
    <div class="elem"><a>4</a></div>
    <div class="elem"><a>5</a></div>
</div>
<div id="copy"></div>
<div id="copy-correct"></div>

<script>
// sort order is not guaranteed here and may vary with browser  
$('#copy').append($('#orig .elem')
          .clone()
          .children('a')
          .prepend('foo - ')
          .parent()
          .clone()); 
 
// correct way to approach where order is maintained
$('#copy-correct')
          .append($('#orig .elem')
          .clone()
          .children('a')
          .prepend('bar - ')
          .end()); 
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .clone() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .clone()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • smnh

    Does .clone(true) also copies event handlers of descendant elements?

    • http://fetzig.at/ fetzig!

      it should. bit not in my case :(

      it does, but be aware that functions like .html() drop Data and Events from the nodes.

  • Arina

    Hi
    When I clone a , is it possible to remove the ‘unique’ class of the cloned div ??

    • Matt

      Arina:
      $(selector).clone().removeClass(‘unique’);
      that should do it for you.

  • http://twitter.com/alexsandro_xpt Alexsandro

    This is a shollow copy or deep copy of DOM Elements?
    Cos javascript cloneNode has a diferent behavior.
    So, what's diferent between cloneNode and clone method?

    • viphe

      From the code, it seems it is a deep copy (uses cloneNode(true) underneath).

      I don't believe such an information should be part of the “figure it out yourself” category (or else, why document anything?).

  • http://twitter.com/sroucheray Stephane Roucheray

    It should be documented here that, on IE < 8, name attributes previously dynamically changed are not copied when using the clone method (instead the original name is copied). The following decoration, while not being a descent solution, can help workaround the issue :
    jQuery.fn.cloneWithAttribut = function( withDataAndEvents ){
    if ( jQuery.support.noCloneEvent ){
    return $(this).clone(withDataAndEvents);
    }else{
    $(this).find(“*”).each(function(){
    $(this).data(“name”, $(this).attr(“name”));
    });
    var clone = $(this).clone(withDataAndEvents);

    clone.find(“*”).each(function(){
    $(this).attr(“name”, $(this).data(“name”));
    });

    return clone;
    }
    };

  • http://twitter.com/reinhardswegler Reinhard Schwegler

    Hello ,

    I do clone an item by dragging it , the new , cloned item should not further create clones …
    how s that to do?

    R.S.

  • Lars

    What if one clones with event handlers but the new handler needs a new id.
    Eg. a select that gets data based on a former select. You clone that and the event that clones with (so to speak) will still point to the former row's select.

  • Dark Nemesis

    How i could clone an input and delete the “value” content?

    • Anthony

      try this :
      var clone = $(selection).clone(true);
      clone.html(clone.html());

  • Zac

    As pointed out at http://welcome.totheinter.net/2009/03/19/the-undocumented-life-of-jquerys-append/, appending a clone to an HTML element will MOVE the clone node into the element to which you append, removing the clone’s original from it’s source.

  • Zac

    I don’t know if it will work for others, but the below code seemed to get around my earlier comment about appending moving a node instead of copying it.
    I needed to remove a child element, check for scrolling, then replace that child and THEN prepend a copy of that child to another div.

    I created TWO clones, one to reinsert into its parent, another to prepend to another different HTML element:

    //get the last child of the current node
    //firstcontainer is a div that contains html
    nodeChildren = $(firstcontainer).children();
    tmpChild = $(nodeChildren)[$(nodeChildren).length-1];
    //a clone of the current node’s last child
    curChild = $(tmpChild).clone();
    //a second clone to use elsewhere
    curChild2 = $(tmpChild).clone();
    //remove child element from parent elem
    $(tmpChild).remove();
    //if scrolling stops, return removed child node
    $(firstcontainer).append(curChild);
    //also prepend the child node to another container element
    $(secondcontainer).prepend(curChild2);

  • Guest

    How to remove/delete a cloned object after dragging

  • http://911-need-code-help.blogspot.com/ Salman

    In IE7/8, I try to clone a DIV that contains various elements, including an empty DIV. In this browser, the height of the original object is correctly returned as 30px but the height of the cloned object is returned as 45px. The extra 15px come from the empty DIV tag that does not contain any text or whitespace (FYI, a div with one line of text is being rendered 15px tall). Any workaround on this?

  • raymond loves ponce

    can i used the clone() function on the add to cart?just like dragging it up on the addtocart?i 'm just wondering if this methods really works..

  • Muzietto

    After wasting some time, I found out how to clone not-DOM objects:
    http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
    Look at John Resig's answer.

  • john

    muy eficiente este metodo

  • Hajdarivn

    What parameter can you pass to clone() such that the events are unbound?

  • Anthony

    try this :
    var clone = $(selection).clone(true);
    clone.html(clone.html());

  • duo

    Why do I use appendTo () , the content is not moved to another place completely?

  • duo

    it is between the two documents(not in a document),i use the appendTo,it shows this problem.

  • duo

    Who can help me? Can not be more grateful to you !

  • http://www.learningjquery.com/ Karl Swedberg

    Since I was replying to a specific person with a specific level of expertise, I felt that the link was perfectly appropriate. This is not the place for support requests, as the big note above the comments explains. If you would like further explanation, please ask at http://forum.jquery.com/

    Thanks.

  • Jameschamp

    do something like $('input').val('”")

  • Mbaynton

    FWIW, I just hit this page from Google with exactly the same question, and now get to ALSO go figure it out for myself…

  • Anon

    I don`t know a lot about the rules around here, but with so many people having the same question it seems like this request was more of a request for clarification of the docs than a request for support on something specific.

  • http://twitter.com/lcmiller lcmiller

    Try this:
    (INPUT = the selector for your input, CONTAINER = selector for where you would like to clone the input)

    code:
    $(INPUT).clone().val('').appendTo(CONTAINER);