Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to insert a row in an HTML table body in JavaScript.

In this article, we’ll look at how to insert a row in an HTML table body in JavaScript.

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

To insert a row in an HTML table body in JavaScript, we can use the insertRow and insertCell methods.

For instance, we 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);

to get the tbody element with

const tbodyRef = document
  .getElementById("myTable")
  .getElementsByTagName("tbody")[0];

Then we call insertRow to insert a tr element into the tbody element.

And then we call newRow.insertCell to insert a td element into the tr element.

Then we call createTextNode to create a text node.

Finally, we use

newCell.appendChild(newText);

to insert the text node into the td element.

Conclusion

To insert a row in an HTML table body in JavaScript, we can use the insertRow and insertCell methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *