The HTML DOM cloneNode() method is used for creating a copy of a given node on which cloneNode() method is called upon and it returns the clone. The cloneNode() method clones all the attributes and values of a given node.
Syntax
Following is the syntax for cloneNode() method −
yourNode.cloneNode([deep])
Here, deep is an optional parameter. By setting its value true we specify that the given node and its children along with their attributes and values should be cloned and by setting its value false we specify that we only want to copy the given node and its attributes and values and not its child nodes.
Example
Let us see an example for the HTML DOM cloneNode() method −
<!DOCTYPE html> <html> <head> <title>CLONE NODE</title> <style> h1{color:green;} h2{ color:blue; } </style> </head> <body> <div id="DIV1"> <h1> HEADING 1</h1> <h2> HEADING 2</h2> </div> <button onclick="CloneEle()"> CLONE </button> <script> function CloneEle() { var x= document.getElementById("DIV1"); var clone = x.cloneNode(true); document.body.appendChild(clone); } </script> </body> </html>
Output
This will produce the following output −
On clicking CLONE button −
In the above example −
We have created a div and have <h1< and <h2< elements inside it. The <h1< and <h2< element have their own styles.
h1{color:green;} h2{ color:blue; } <div id="DIV1"> <h1> HEADING 1</h1> <h2> HEADING 2</h2> </div>
We have then created a button CLONE that will execute the function CloneEle() when clicked by the user −
<button onclick="CloneEle()"> CLONE </button>
The CloneEle() method will get the div element by using the getElementById() method and assigns it to variable x. We then use the cloneNode(ture) method on the <div> with parameter true to clone it and its children elements and assign them to variable clone. The clone variable is then appended to the document body using the appendChild() method −
function CloneEle() { var x= document.getElementById("DIV1"); var clone = x.cloneNode(true); document.body.appendChild(clone); }