0

With JavaScript, I attached functions to two buttons, one of which adds rows to a table. However, I somehow made it to add rows from the bottom, so when you click it, it stacks the rows on top of each other from the top. I'm looking for the table rows to be stacked from top to bottom, so that it increases in length in the bottom, not the top. How do you do this?

In case it's not clear, here's a JSFiddle (I want the rows to appear below the Headers, not above): http://jsfiddle.net/yvzq03LL/

HTML

  <table id="myTable">
  <tr>
    <td>Header 1</td>
    <td>Header 2</td>
  </tr>
</table>

<br>

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

CSS

table, td {
  border: 1px solid black;
}

JavaScript

function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "Added row";
    cell2.innerHTML = "Added row";
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(0);
}
Shrey
  • 522
  • 8
  • 16

2 Answers2

2

Well, I figured it out. Where it says var row = table.insertRow(), there has to be a 1 inside inside of a 0. My guess is that since Row 0 are the Headers, Row 1 would be the next one. Correct me if I'm wrong anyone.

function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "Added row";
    cell2.innerHTML = "Added row";
}
Shrey
  • 522
  • 8
  • 16
  • 1
    This will always add it in that position (1st position). Use -1 as your index, or leave it empty. https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow – Hanlet Escaño Jul 28 '15 at 01:52
0

Just change insertRow(0) to insertRow(-1)

w35l3y
  • 8,613
  • 3
  • 39
  • 51