0

The following HTML file contains an add button. When clicked, it should add a row. When I inspect the code, I find the rows added under the thead not the tbody tag. Why is that? how to avoid this?

addButton = document.getElementById("add-button");
table = document.getElementById("data-table");

addButton.addEventListener('click', add, false);

function add() {

  var tableLength = table.length;
  var row = table.insertRow(tableLength);

  var col1 = row.insertCell(0);
  var col2 = row.insertCell(1);

  col1.innerHTML = "col1";
  col2.innerHTML = "col2";
}

var delLink = document.getElementById("delete-link");
delLink.addEventListener('click', del, false);

function del() {
  var rowstoDelete = table.querySelectorAll("tbody tr");
  [].slice.call(rowstoDelete).forEach(function(row) {
    row.remove()
  });

}
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
  <thead>

    <tr id="head" class="head">
      <th class="head">Name</th>
      <th class="head">Action</th>
    </tr>

    <tr id="initial-row" class="initial-row">
      <th><input type="text" id="text-field"></th>
      <th><input type="button" class="add-button" id="add-button" value="Add"></th>
    </tr>

  </thead>

  <tbody>

  </tbody>

</table>

<a id="delete-link" href="#"> Delete all rows Except the first two</a>
George
  • 6,630
  • 2
  • 29
  • 36
user7945230
  • 1,075
  • 2
  • 13
  • 20
  • Possible duplicate of [How to insert row in HTML table body in javascript?](https://stackoverflow.com/questions/18333427/how-to-insert-row-in-html-table-body-in-javascript) – George Jun 01 '17 at 10:23
  • `insertRow()` appends to the parent of the row identified by the index. Since the existing row is in `thead`, that's what `insertRow()` appends to. – Barmar Jun 01 '17 at 10:26
  • BTW, you can use `-1` instead of `tableLength` to mean you want to insert at the end. – Barmar Jun 01 '17 at 10:26

1 Answers1

3

check my fiddle here enter link description here

What you didnt did is to see specifically for tbody. Answered here How to insert row in HTML table body in javascript?

    addButton=document.getElementById("add-button");
table=document.getElementById("data-table");

addButton.addEventListener('click',add,false);

function add()
{

    var tableLength=table.length;
    var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);

    var col1 = row.insertCell(0);
    var col2 = row.insertCell(1);

    col1.innerHTML="col1";
    col2.innerHTML="col2";
}

var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);

function del()
{
    var rowstoDelete = table.querySelectorAll("tbody tr");
    [].slice.call(rowstoDelete).forEach(function(row) {
    row.remove()
    });

}
Panagiotis Vrs
  • 824
  • 6
  • 16