cloneNode

In this chapter you will learn:

  1. How to clone a node

Clone a node

You can use the cloneNode method to duplicate existing elements.

<!DOCTYPE HTML> <!--from   j  av a  2  s .  co m-->
<html> 
<body> 
<table border="1"> 
    <tbody id="SurveysBody"> 
        <tr><td class="sum">A</td><td class="result">B</td></tr> 
    </tbody> 
</table> 
<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

Next chapter...

What you will learn in the next chapter:

  1. How to create a new HTML element
Home » Javascript Tutorial » HTML Operation
HTMLElement
addEventListener
appendChild
attributes
classList
className
cloneNode
createElement
createTextNode
dataset
getAttribute
getElementsByTagName
hasAttribute
innerHTML
insertAdjacentHTML
insertBefore
isSameNode
outerHTML
onmouseout
onmouseover
removeEventListener