Sometimes, we want to insert a row in an HTML table body with JavaScript.
In this article, we’ll look at how to insert a row in an HTML table body with JavaScript.
Call the insertRow and insertCell Methods
JavaScript DOM API has the insertRow
method built into the tbody
element.
And it also has the insertCell
method built into the tr
element.
insertRow
lets us insert a new table row.
And insertCell
method lets us insert a new cell into a table row.
For instance, if we have the following HTML:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
We can write:
const tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const newRow = tbodyRef.insertRow();
const newCell = newRow.insertCell();
const newText = document.createTextNode('new row');
newCell.appendChild(newText);
We have a table, with the tbody
element inside.
Then to get the tbody
, we call getElementId
to get the table.
Then we call getElementsByTagName
to get the tbody
element.
Next, we call insertRow
on the tbody
element to create a new tr
.
And then we call insertRow
on the newly created tr
.
Next, we call document.createTextNode
to create a new text node for the table cell content.
And then we call newCell.appendChild
to append the newText
text node.
Now we should see ‘new row’ before the footer.
Conclusion
We can use methods built into tbody
and tr
DOM objects to insert new table rows and cells with JavaScript.