Working with Tables

FireFox lets you add rows to a table simply by using the innerHTML property of the table object:

function addRow()
{
 
  var table = document.getElementById('data_table');
 
  table.innerHTML += '<tr>';
  table.innerHTML += '<td>Cell 1</td>';
  table.innerHTML += '<td>Cell 2</td>';
  table.innerHTML += '</tr>';
 
}

<table id="data_table">
  <tr>
    <td>Cell 1</td>
    <td>Cell 2</td>
  </tr>
</table>
 
<p>
  <button type="button" onclick="addRow()">Add a Row</button>
</p>

Unfortunately, this is not allowed under a strict interpretation of the aforementioned DOM, which means that this shortcut is not necessarily supported by all browsers. In particular, Internet Explorer does not support innerHTML on tables or table rows.

Fixing this is pretty easy, and in fact using the ‘correct’ method of interacting with tables, cells and rows makes life a lot more exciting when manipulating tables in the long run:

function addRow()
{
 
  var table = document.getElementById('data_table');
 
  // get the number of rows already in the table
  var num_rows = table.rows.length;
 
  // insert a new row at the bottom of the table
  // and assign a variable to refer to it
  var new_row = table.insertRow(num_rows);
 
  // insert the first cell to the new row
  // and then put content in the cell
  var new_cell = new_row.insertCell(0);
  new_cell.innerHTML = "Cell 1";
 
  // insert the second cell to the new row
  // and then put content in the cell
  new_cell = new_row.insertCell(1);
  new_cell.innerHTML = "Cell 2";
 
}

The insertRow(index) method lets you insert a row at any point you want by passing the index variable (in the above example we use the number of rows to set the index to add a new row at the bottom). You could insert at the top of the table by passing an index of 0, or anywhere else in the table by passing the relevant index (upto the number of rows in the table).

There’s a lot more you can do working this way through the DOM that you’d miss with the innerHTML methods that FireFox uses – deleteRow and deleteCell, for one. Plus there are methods to create and delete the table caption, table footer, table header, and table bodies.

A complete reference can be found at W3Schools.