How to insert row at end of table with HTMLTableElement.insertRow with JavaScript?

Sometimes, we want to insert row at end of table with HTMLTableElement.insertRow with JavaScript.

In this article, we’ll look at how to insert row at end of table with HTMLTableElement.insertRow with JavaScript.

How to insert row at end of table with HTMLTableElement.insertRow with JavaScript?

To insert row at end of table with HTMLTableElement.insertRow with JavaScript, we can call insertRow with -1.

For instance, we write:

<table>
  <tbody></tbody>
</table>

to add a table.

Then we write:

const data = [{
    "a": 1,
    "b": 2,
    "c": 3
  },
  {
    "a": 4,
    "b": 5,
    "c": 6
  },
  {
    "a": 7,
    "b": 8,
    "c": 9
  }
]

const table = document.querySelector('table')
for (const d of data) {
  const row = table.insertRow(-1);
  for (const c of Object.values(d)) {
    const cell = row.insertCell(-1);
    cell.textContent = c
  }
}

to select the table with querySelector.

Then we loop through the data array with a for-of loop.

In the loop, we call insertRow with -1 to append a row to the table.

Then we loop through the property values for each data entry that we got from Object.values to insert the cells.

We append a cell to the row by calling row.insertCell with -1.

And then we set the textContent to c.

As a result, we see:


1	2	3
4	5	6
7	8	9

displayed.

Conclusion

To insert row at end of table with HTMLTableElement.insertRow with JavaScript, we can call insertRow with -1.