How to insert a row in an HTML table body in JavaScript

Jérôme Verstrynge picture Jérôme Verstrynge · Aug 20, 2013 · Viewed 357.5k times · Source

I have an HTML table with a header and a footer:

<table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>

I am trying to add a row in tbody with the following:

myTable.insertRow(myTable.rows.length - 1);

but the row is added in the tfoot section.

How do I insert tbody?

Answer

Jonathan Naguin picture Jonathan Naguin · Aug 20, 2013

If you want to add a row into the tbody, get a reference to it and call its insertRow method.

var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>initial row</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My Footer</td>
    </tr>
  </tfoot>
</table>

(old demo on JSFiddle)