Search code examples
javascripthtmlprepend

HTML - how to insert rows in a prepend manner?


I'm trying to add a new set of rows below the original one's and have a delete function together w/ the add function. Luckily I bumped into an article of w3schools : http://www.w3schools.com/jsref/met_table_insertrow.asp

However it adds the new cells above the original one's, how can I tweak it to make it work?

CODE:

<table id="myTable" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table><br>

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>

<script>
function myCreateFunction()
{
var table = document.getElementById("myTable");
  {
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
  }
}
function myDeleteFunction()
{
document.getElementById("myTable").deleteRow(0);
}
</script>

Solution

  • var row = table.insertRow(0); // 0 represent the 0th index and hence it add at top
    

    change it to

    var tdsLength = table.getElementsByTagName('tr').length;
    var row = table.insertRow(tdsLength);  //change it to last index
    

    or

    var row = table.insertRow(-1);
    

    From Docs, If index is -1 or equal to the number of rows, the row is appended as the last row. JSFiddle