Search code examples
javascriptclone

How to change childNodes in JavaScript?


how can I clone the table and automatic increase the #changeThis number when I click the button?

This is my example of problem

<button type="button" onclick="cloneTable()">clone Table</button>
<table>
  <tr>
    <th id="changeThis">1</th>
    <td><select name="" size="1"><option></option></select><input type="text"></td>
  </tr>
</table>

Thank you


Solution

  • You have to use cloneNode method.

    var i=1;
    function cloneTable(){
       var table = document.getElementById("table1");
       var clone = table.cloneNode(true);
       clone.id="table"+ ++i;
       document.body.appendChild(clone);
       document.querySelector('#table' +i+' th ').innerHTML=i;
    }
    <button type="button" onclick="cloneTable()">clone Table</button>
    <table id="table1"><tr><th class="changeThis">1</th><td><select name="" size="1"><option></option></select><input type="text" ></td></tr></table>