The jQuery clone() method can be used to make a copy of the selected element. The copies content also includes the element child nodes, texts, and attributes. It is useful when you want to create clones of the elements.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters is given below.
Parameter Name | Description |
---|---|
selector | You have to specify the element to select and make a clone. Use tag name, class name, or id of the elements to select. |
true | Specify the boolean value to including the event handler when copying the element. |
jQuery clone() Method to Copy Selected Element
If you want to make copies of the selected element without including the event handlers, you can use the example given below. The example creates the clone of the paragraph element until you click the button.
Example
1 2 3 4 5 6 7 8 9 10 |
<script> $(document).ready(function(){ $('.clonebtn').click(function(){ $("p").clone().appendTo("div"); }); }); </script> <p>This is my paragraph.</p> <button type="button" class="clonebtn">Click to Clone</button><br><br> <div></div> |
Output
This is my paragraph.
When you click the button given above, it creates a copy of the element and appends it to the div element. You can create multiple copies by clicking the element for more than one time.
Copy an Element Including Event Handler
You can also add events with the copies elements like animation and other effects. To perform this task, you have to pass ‘true’ as the parameter of the jQuery clone() method.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<script> $(document).ready(function(){ $('.cloneeventbtn').click(function(){ $("div").append($("p").clone(true)); }); $("p").click(function(){ $(this).animate({height: "+=20px"}); }); }); </script> <style> p{ border:1px solid #ccc; } </style> <p>This is my paragraph.</p> <button type="button" class="cloneeventbtn">Click to Clone with Event Handler</button><br><br> <div></div> |
Output
This is my paragraph.
Click the button given above to make the clone of the selected element. The clone also contains the animation effect of the original element. If you click the paragraph, it animates the clone and increases the height of the selected element.
You may also like to read
I hope you like this tutorial on jQuery clone() method. If you have any queries regarding the tutorial, please comment below.
References