How to clone a node in Javascript

Clone a node

You can use the cloneNode method to duplicate existing elements.

Example


<!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  . ja v a2  s. c  om-->
<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>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window