jQuery

jquery .clone() Method Examples

jQuery clone method is an easy way to duplicate elements on a page. It performs a deep copy of the set of matched elements. In other words, it copies the matched elements as well as all of their descendant elements and text nodes to duplicate the elements. In this article, I am going to share easy examples that show how to use the clone method.

How to use the jQuery clone method

In order to clone contents of an element, it is necessary to have an element first. So for example, if you want to clone a div along with all it’s contents, we will need a div with some content. If you don’t have any content in that div, it’s clone won’t contain any content either. So let’s see how to create clones by means of some examples.

Common HTML source code for all the following examples:

<style type="text/css">
.red {
background-color: #FFA6A6;
border: 1px solid red;
margin: 10px;
}
.green {
background-color: #CEFFCE;
border: 1px solid green;
margin: 10px;
}
</style>

<div id="mydiv1" class="red">This is MY DIV 1</div>

<div id="mydiv2" class="green">This is MY DIV 2</div>

<ul id="my_list">
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>

<div id="new_list_container"></div>

</div>

<p>
<input type="submit" name="sbt_create_div1_clone" id="sbt_create_div1_clone" value="Create DIV 1 Clone and Insert it after DIV 1">
<br>

<input type="submit" name="sbt_prepend_clone" id="sbt_prepend_clone" value="Create DIV 1 Clone and Prepend it to DIV 2">
<br>

<input type="submit" name="sbt_append_clone" id="sbt_append_clone" value="Create DIV 1 Clone and Append it to DIV 2">
<br>

<input type="submit" name="sbt_clone_list" id="sbt_clone_list" value="Create LIST Clone in a DIV and Add one NEW LIST ITEM to the Clone">

<br>

<input type="button" name="sbt_reset" id="sbt_reset" value="Reset everything">

</p>

Example 1: Create a Div clone and insert the clone immediately after the Div itself

	$('#sbt_create_div1_clone').on("click", function(){

		$('#mydiv1').clone().insertAfter("#mydiv1");

	});

Example 2: Create a Div clone and Prepend it to another Div

	$('#sbt_prepend_clone').on("click", function(){

		$('#mydiv1').clone().prependTo('#mydiv2');

	});

Example 3: Create a Div clone and Append it to another Div

	$('#sbt_append_clone').on("click", function(){

		$('#mydiv1').clone().appendTo('#mydiv2');

	});

Example 4: Create a List clone in a Div and one new custom list item to the Clone

	$('#sbt_clone_list').on("click", function(){

		( $('#my_list').clone().append('<li>List Item 4</li>') ).appendTo('#new_list_container');

	});
That’s it!

Do you know of any other ways to use the jQuery .clone() method? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*