Javascript Element How to - Add row to Table








Question

We would like to know how to add row to Table.

Answer


<!DOCTYPE html>
<html>
<body>
  <table id="table">
    <tr id="firstRow">
      <td>One</td>
      <td>Two</td>
    </tr><!--  ww w  .j  a  v  a 2  s  .  c  om-->
  </table>
    <script type='text/javascript'>
    var html = "<tr><td>Three</td><td>Four</td></tr>";
    var table = document.getElementById("table");
    var range = document.createRange();
    range.selectNodeContents(table);
    var frag = range.createContextualFragment(html);
    table.appendChild(frag);
    
    </script>

</body>
</html>

The code above is rendered as follows: