How to insert row in HTML table body in JavaScript

How to insert row in HTML table body in JavaScript

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

My Header
My footer

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?


Solution 1:

If you want to add a row into the tbody, get a reference to it and add it there.

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

// Insert a row in the table at the last row
var newRow   = tableRef.insertRow();

// Insert a cell in the row at index 0
var newCell  = newRow.insertCell(0);

// Append a text node to the cell
var newText  = document.createTextNode('New row');

A working demo here.
Also you can check the documentation of insertRow here.

Solution 2:

You can try following snippet using Jquery.

$(table).find('tbody').append( "<tr><td>aaaa</td></tr>" );

Solution 3:

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 at jsFiddle.

Solution 4:

Basic Approach:

This should add html formatted content and show 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;

Solution 5:

I think this script is what exactly you need

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

Solution 6:

I have tried this,

this is working for me

var table=document.getElementById("myTable");
var row=table.insertRow(myTable.rows.length-2);
var cell1=row.insertCell(0);