jQuery clone example
The aim of this example is to show you how to use the jQuery .clone()
method .
Sometimes we need to copy the HTML element and work with the copied element. The jQuery .clone()
method is used for this purpose.
This 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.
Let’s look at some examples. To download the jQuery library, click here.
1. HTML
First of all you need to create a simple html document.
<!DOCTYPE html> <html> <head> <script src="jquery-2.1.4.min.js"></script> <style type="text/css"> .container{ padding:10px; border:2px solid #f00; margin:10px; width:300px; } </style> </head> <body> <div class="container"> <a href="http://www.google.com" >Google</a><br/> </div> </body> </html>
2. jQuery clone examples
2.1 clone the div element
Let’s add the following simple html code.
<button id="cloneDiv">clone()</button>
In the following jQuery code, the jQuery .clone()
method has been used to copy the container element and insert it into the HTML document.
<script type="text/javascript"> $("#cloneDiv").click(function () { $('.container').clone().insertAfter(".container"); }); </script>
The result in the browser would be:
2.2 clone the button element with event handler
Let’s add the following simple html code.
<button id="cloneButton1">clone(true) button with event handler</button>
As you can notice in the following code. In the line 7, we are passing true value to .clone()
method. This tell .clone()
to copy the HTML element with it’s event handler .
<script type="text/javascript"> $("#cloneDiv").click(function () { $('.container').clone().insertAfter(".container"); }); $("#cloneButton1").click(function () { $('#cloneDiv').clone(true).insertAfter("#cloneDiv"); }); </script>
The result in the browser would be:
2.3 clone the button element without event handler
Let’s add the following simple html code.
<button id="cloneButton2">clone(false) button without event handler</button>
If we want to copy the html element without it’s event handler, we can pass a “false” value to .clone()
method or call it without passing any argument.
<script type="text/javascript"> $("#cloneDiv").click(function () { $('.container').clone().insertAfter(".container"); }); $("#cloneButton2").click(function () { $('#cloneDiv').clone(false).insertAfter("#cloneDiv"); }); </script>
The result in the browser would be: