How to add a row on top of table generated by JavaScript?

Sometimes, we want to add a row on top of table generated by JavaScript.

In this article, we’ll look at how to add a row on top of table generated by JavaScript.

How to add a row on top of table generated by JavaScript?

To add a row on top of table generated by JavaScript, we call the insertRow method.

For instance, we write

const myTable = document.getElementById("myTable");
const tbody = myTable.tbodies[0];
const tr = tbody.insertRow(-1);

const td = document.createElement("td");
td.innerHTML = "Something";
tr.appendChild(td);

to select the table with getElementById.

Then we get the tbody element in it with myTable.tbodies[0].

Next, we call insertRow with -1 to insert the tr as the first child of the tbody element.

Then we create a td element with createElement and then call appendChild to append it as the last child of the tr.

We set its content by setting the innerHTML property.

Conclusion

To add a row on top of table generated by JavaScript, we call the insertRow method.