DEV Community

Noé Melo Locumber
Noé Melo Locumber

Posted on

How to insert rows in an HTML table body in JavaScript

HTML code of the table with a only row:

<table class="table" id="myTable">
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
        <th scope="row">1</th>

Here JavaScript code:

    var first_names = ['Jacob','Mark','Noé'];
    var last_names = ['Thornton','Otto', 'Melo'];
    var handle_names = ['@fat','@mdo','@noemelolocumber'];

    //get table body:
    var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

    for (let index = 0; index < first_names.length; index++){
        //insert Row
        tableRef.insertRow().innerHTML = 
        "<th scope='row'>" + (index + 2).toString()+ "</th>" + 
        "<td>" +first_names[index]+ "</td>"+
        "<td>" +last_names[index]+ "</td>"+
        "<td>" +handle_names[index]+ "</td>";

Alt Text

Top comments (4)

madeinmilwaukee profile image
Chuck Watson

Worth noting that you do not need to reference the tbody directly if the table has only one tbody. It would be useful to see this tutorial using insertCell and avoiding the html in the script, as is outlined here

noemelo profile image
Noé Melo Locumber

Good observation, however, when using the function insertCell and createTextNode the css styles of the table are lost.

howardb1 profile image
Howard Brown

As far as this goes. that being that you know all of the table rows' content you want to add as a string to the tbody, so can just assign a string to the innerHTML property of an inserted row, fine. However, if you want to add an existing row object, say one clowned from another table, but don't want to revert to getting a string version of the existing row and appending it to the end of the innerHTML of the tbody's insertRow, how would you suggest doing that?

howardb1 profile image
Howard Brown

Also, how can I insert the new tr element between two existing comment nodes?