Add Table Rows and Cells with JavaScript



In this article, you will learn how to add table rows and cells with JavaScript.

The HTMLTableElement.insertRow() method

The HTMLTableElement.insertRow () method is a method to add a new row to an HTML table and returns the tr element of the added row as a return value.
When you execute this method, an empty tr tag is added.

The syntax is below.


Also, if you pass a number as an argument, you can add it to the specified line.
If 0 is specified as an argument, it can be added to the first row of the table, and if 1 is specified, it can be added to the second row.

The HTMLTableRowElement.insertCell() method

The HTMLTableRowElement.insertCell () method is a method to add a cell to a row in an HTML table.

The syntax is below.


You can add a cell to the specified column by passing a number as an argument.

Sample Code

Below is sample code that inserts a row to a two-column HTML table and adds a value to each cell.

let myTable = document.getElementById('targetTable');
let newRow = myTable.insertRow();

let newCell = newRow.insertCell();
let newText = document.createTextNode('foo');

newCell = newRow.insertCell();
newText = document.createTextNode('bar');