The clone() method is used to make duplicate copy of selected elements. Means it copies the matched elements as well as their descendant elements and text nodes. It copies child nodes, text and attributes of the selected elements. It clones matched DOM elements and select the clones. It is also useful for moving elements into other location in the DOM. It is convenient way to make deep copy of elements on the page.
JQuery Clone() Syntax
$(selector).clone().childnode();
It has parameter called childnode is the required parameter which include childnode, text attributes.
JQuery Clone() Example
<!doctype html> <head> <title>JQuery Clone Method</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <h2>JQuery Clone Method Example</h2> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("<p>Welcome to JavaBeat!!!</p>").clone().insertBefore("h3"); }); }); </script> <body> <h3>Hello!!!</h3> <button>Click Here</button> </body> </html>
- As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
- $(“button”).click(function()) line defines click event which occurs when button is clicked.
- $(“Welcome to JavaBeat!!!”).clone().insertBefore(“h3”); line defines clone method used to make duplicate copy of selected elements. It inserts the line Welcome to JavaBeat!!! before the line Hello!!!.
JQuery Clone() Demo
When you run the above example, you would get the following output:
The clone() method is also used to make duplicate copy of selected elements with appendTo() method as shown in the below example:
<!doctype html> <head> <title>JQuery Clone Method</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <h2>JQuery Clone Method Example</h2> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("<strong>Welcome to JQuery!!!</strong>").clone().appendTo(".myappend"); }); }); </script> <body> <button>Insert element to the end of p element</button> <div class="myappend"> <p>Hello World!!!</p> </div> </body> </html>
In above example, we have used clone() method with appendTo() method which will make deep copy of selected elements. The appendTo() method indicates JS interpreter to append the content in quotes to div class elements. When you run the script, click on the button which will appear on the browser, the line Welcome to JQuery!!! appends after the line Hello World!!!