Coder Perfect

In JavaScript, how do you insert a row in the body of an HTML table?


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

<table id="myTable">
            <th>My Header</th>
            <td>My footer</td>

I’m trying to add a row to tbody that looks like this:

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

The row, however, is appended to the tfoot section.

How do I add tbody to my page?

Asked by Jérôme Verstrynge

Solution #1

Get a reference to the tbody and call its insertRow method if you wish to add a row to it.

(ancient JSFiddle demo)

Answered by Jonathan Naguin

Solution #2

You can use jQuery to create the following snippet:


Answered by Sasidharan

Solution #3

Basic approach:

This should display the newly inserted row and add HTML-formatted information.

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

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

Answered by Kurkula

Solution #4

You’re almost there. Just add the row to the tbody instead of table:


Before using, get a reference to tBody (myTbody). It’s worth noting that you don’t need to pass the table’s last position; when the argument is omitted, the table is automatically positioned at the end.

jsFiddle has a live demo.

Answered by Teemu

Solution #5

I believe this script is just what you require.

var t = document.getElementById('myTable');
var r =document.createElement('TR');

Answered by Marwan

Post is based on