js insert row at top of table code example

Example 1: javascript insert row at end of table

<table id="ThisTable">
  <tr><th>Head1</th><th>Head2</th><th>Head2</th></tr>
  <tr><td>Data1</td><td>Data1</td><td>Data1</td></tr>
  <tr><td>Data2</td><td>Data2</td><td>Data2</td></tr>
</table>
<script>
  var table = document.getElementById("ThisTable");
  var row = table.insertRow(-1);
  <!-- Filling the new created cell -->
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
  cell3.innerHTML = "NEW CELL3";
</script>
<!-- The (-1) indexes the last position of the table -->

Example 2: javascript insert table row at index

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";