How to insert a row in an HTML table body in JavaScript
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 tablevar newRow = tbodyRef.insertRow();// Insert a cell at the end of the rowvar newCell = newRow.insertCell();// Append a text node to the cellvar 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)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
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;