clone()

  •   Create a deep copy of the set of matched elements.
  •   We can use clone copy in to two ways,clone()/clone(true).It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.First we see the clone()

METHOD 1 :  clone()

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

HTML :

<div>
<p>Testing for clone() method in jquery
</div>

JQUERY :

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

OUTPUT DOM :

<div>
<p>Testing for clone() method in jquery</p>
</div>

<div>
<p>Testing for clone() method in jquery
</div>

NOTE:
After executing JQ, the element which has class name as mainDiv will be copied and placed after the element which has class name of mainDiv

METHOD 2: clone(boolean)
It also support a boolean parameter to indicate whether need to copy the event handlers and data along with the matched elements.

HTML :

<button id=”cloneBtn”>clone()</button>

JQUERY :

$(“#cloneBtn”).click(function () {

$(‘.mainDiv’).clone().insertAfter(“.mainDiv”);

});

STEP 1 : $(‘#cloneBtn’).clone().insertAfter(“#cloneBtn”);

Above will copy only element without any event handler.

STEP 2 ; $(‘#cloneBtn’).clone(true).insertAfter(“#cloneBtn”);

Above will copy event handler along with matched elements, you should use clone(true).

Note : For better understanding

 If we create button dynamically with the clone method,it will copy element and eventhandler(thats is action to be performed ) when we use
clone(true).