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

You can try the following snippet using jQuery:


You're close. Just add the row to the tbody instead of table:


Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.

A live demo is at jsFiddle.

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

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');
<table id="myTable">
      <th>My Header</th>
      <td>initial row</td>
      <td>My Footer</td>

(old demo on JSFiddle)