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 use some methods in the tbody element.

For instance, we write

<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>initial row</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My Footer</td>
    </tr>
  </tfoot>
</table>

to add a table.

Then we write

const [tbodyRef] = document
  .getElementById("myTable")
  .getElementsByTagName("tbody");
const newRow = tbodyRef.insertRow();
const newCell = newRow.insertCell();
const newText = document.createTextNode("new row");
newCell.appendChild(newText);

to get the tbody element ofi the table with getElementsByTagName.

Then we call insertRow to create a new tr element as the tbody’s ast child.

We call insertCell to insert a new td element into the tr element as its last child.

Then we call createTextNode to create a text node.

Finally we use newCell.appendChild(newText) to insert the text node into the td cell.

Conclusion

To insert a row in an HTML table body in JavaScript, we use some methods in the tbody element.

Leave a Reply

Your email address will not be published.