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

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>