jQuery clone() is used to create a copy of the matched elements. It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.

1. Clone the html elements

For example, you are going to clone the following html code.

 <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div>

Use clone() to create a copy of the above elements, and put the copied elements after the div tag that contains a class name of “smallBox”.

$('.smallBox').clone().insertAfter(".smallBox");

The result :

 <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div>
  <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div>

2. Clone the event handler

The next example will be cloning the button click event, you are going to copy the button that contains a id of ‘cloneButton1′.

<button id="cloneButton1">clone()</button>
 
<script type="text/javascript">
    $("#cloneButton1").click(function () {
 
	  $('.smallBox').clone().insertAfter(".smallBox");
 
    });
</script>

If you are using the default clone() or clone(false) method, it will copy the button element only, but not the click() event handler.

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

To copy the click() event handler along with matched elements, you should use clone(true).

$('#cloneButton1').clone(true).insertAfter("#cloneButton1");

Try it yourself

<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 
<style type="text/css">
	.smallBox{
		padding:8px;
		border:1px solid blue;
		margin:8px;
	}
	.smallInnerBox{
		padding:8px;
		border:1px solid green;
		margin:8px;
	}
</style>
 
</head>
<body>
  <h1>jQuery clone() example</h1>
 
  <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
   </div>
 
  <p>
  <button id="cloneButton1">clone()</button>
  <button id="cloneButton2">clone() button (default)</button>
  <button id="cloneButton3">clone(true) button</button>
  <button id="reset">reset</button>
  </p>
 
<script type="text/javascript">
 
    $("#reset").click(function () {
	  location.reload();
    });
 
    $("#cloneButton1").click(function () {
 
	  $('.smallBox').clone().insertAfter(".smallBox");
 
    });
 
    $("#cloneButton2").click(function () {
 
	  $('#cloneButton1').clone(false).insertAfter("#cloneButton1");
 
    });
 
    $("#cloneButton3").click(function () {
 
	  $('#cloneButton1').clone(true).insertAfter("#cloneButton1");
 
    });
 
</script>
</body>
</html>
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts