The cloneNode()
method creates a copy of a node, and returns the clone.
cloneNode |
Yes | Yes | Yes | Yes | Yes |
node.cloneNode(deep)
Parameter | Type | Description |
---|---|---|
deep | Boolean | Optional. Default is false.
Set to true to clone the node, its attributes, and its descendants. Set to false to clone only the node and its attributes. |
Return the cloned node in Node object type.
The following code shows how to copy a list item from one list to another.
<!DOCTYPE html>
<html>
<body>
<ul id="myList1"><li>A</li><li>C</li></ul>
<ul id="myList2"><li>B</li><li>D</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!-- w ww.j a va2 s. co m-->
{
var itm=document.getElementById("myList2").lastChild;
var cln=itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
</script>
</body>
</html>
The code above is rendered as follows:
You can use the cloneNode
method to duplicate existing elements.
<!DOCTYPE HTML>
<html>
<body>
<table border="1">
<tbody id="SurveysBody">
<tr><td class="sum">A</td><td class="result">B</td></tr>
</tbody>
</table> <!-- w w w . j ava 2s . c o m-->
<button id="add">Add Row</button>
<script>
var tableBody = document.getElementById("SurveysBody");
document.getElementById("add").onclick = function() {
var count = tableBody.getElementsByTagName("tr").length + 1;
var newElem =
tableBody.getElementsByTagName("tr")[0].cloneNode(true);
newElem.getElementsByClassName("sum")[0].firstChild.data =
count + " + " + count;
newElem.getElementsByClassName("result")[0].firstChild.data =
count * count;
tableBody.appendChild(newElem);
};
</script>
</body>
</html>