jQuery: the clone() method

jQuery provides, among other DOM methods, a simple method to clone an element with all its children. This method is called clone() and accepts as its optional value a Boolean flag that specifies whether event handlers must be cloned along with the elements they're attached to. This flag defaults to false. Bear in mind, however, that even attributes are cloned, so you should use this method carefully. For example, given the following DOM structure:

<div id="test">

  <ul>
  
    <li>A</li>
    <li>B</li>
    <li>C</li>
  
  </ul>

</div>

<div id="target"></div>

We want to clone the test element and its children within the target element. Here's the jQuery code:

$('#run').click(function(e) {
  
  
    var clone = $('#test').clone();
  
    $(clone).appendTo('#target');
    
    e.preventDefault();
  
});

After the cloning has taken place, our DOM structure now appears as follows:

As you can see, attributes have been cloned together with the entire DOM structure. You should always be aware of this fact when using this method. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.