jQuery | clone() with Examples
The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes.
Syntax:
$(selector).clone(true|false)
Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.
Return Value : It returns the cloned elements for the selected element.
Code #1:
In the below code, no true or false is passed to the change method.
<html> <head> jquery/3.3.1/jquery.min.js"></script> <!--In this example no parameter is passing to the clone method--> <script> $(document).ready(function() { $("button").click(function() { $("p").clone().appendTo("body"); }); }); </script> </head> <body> <p>Welcome to</p> <p>GeeksforGeeks !!!</p> <!--click on this method and see the clone element--> <button>Click Me!</button> </body> </html> |
Before clicking the “Click Me” button-

After clicking the “Click Me” button-

Code #2:
In the below code, true is passed to the clone method.
<html> <head> jquery/3.3.1/jquery.min.js"></script> <!--here clone method is called with the true value passing--> <script> $(document).ready(function() { $("button").click(function() { $("body").append($("p:first").clone(true)); }); $("p").click(function() { $(this).animate({ fontSize: "+=1px" }); }); }); </script> </head> <body> <p>GeeksforGeeks !</p> <p>Hello Writer !</p> <!--click on this method and see the clone element--> <button>Click Me!</button> </body> </html> |
In this example code event handler animate will work when you click on the “GeeksforGeeks” and this will also reflect on the cloned elements.
Output:
Before clicking the “Click Me” button-

After clicking the “Click Me” button-

Recommended Posts:
- jQuery | one() with Examples
- jQuery | on() with Examples
- jQuery | last() with Examples
- jQuery | val() with Examples
- jQuery | first() with Examples
- jQuery | has() with Examples
- jQuery | after() with Examples
- jQuery | eq() with Examples
- jQuery | resize() with Examples
- jQuery | replaceWith() with Examples
- jQuery | replaceAll() with Examples
- jQuery | hasClass() with Examples
- jQuery | serialize() with Examples
- jQuery | scroll() with Examples
- jQuery | select() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



