197

I have an HTML table with a header and a footer:

<table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>

I am trying to add a row in tbody with the following:

myTable.insertRow(myTable.rows.length - 1);

but the row is added in the tfoot section.

How do I insert tbody?

1

13 Answers 13

310

If you want to add a row into the tbody, get a reference to it and call its insertRow method.

var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<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>

(old demo on JSFiddle)

8
  • 4
    My code breaks because: Cannot read property 'insertRow' of null. Any suggestions?
    – Vrankela
    Dec 26, 2014 at 13:52
  • 2
    @Vrankela: Probably your selector is incorrect (first line in example). May 15, 2016 at 21:44
  • 2
    the above would fail the first time. instead check if there are no rows: var rows = tableRef.rows; var rowsSoFar = (rows==null) ? 0 : rows.length; var newRow = tableRef.insertRow(rowsSoFar);
    – inor
    Sep 21, 2017 at 10:22
  • 4
    Instead of tableRef.insertRow(tableRef.rows.length); you can simple use tableRef.insertRow(-1); to insert the row at the end of the table.
    – jeanggi90
    Mar 7, 2019 at 12:06
  • 1
    how to insert entire row if i have entire <tr> ... </tr html string for all cell? above code seems to add one cell only.
    – Lei Yang
    Sep 29, 2019 at 6:07
49

You can try the following snippet using jQuery:

$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
4
  • 29
    maybe you are right but sometimes you need to know the real stuff :) and as i say always know JavaScript before the using any library no hard feeling body ;)
    – Marwan
    Aug 20, 2013 at 11:30
  • I'm trying to apply your answer to my case but I couldn't, so I posted a new question, do you think that you can answer it and save me? ► stackoverflow.com/q/63194846/3298930 . Jul 31, 2020 at 15:59
  • What is the syntax if I want a variable in place of aaaa? Nov 11, 2020 at 9:35
  • ...apend("<tr><td>" + myVar + "</td></tr>"); Feb 17, 2022 at 13:13
34

Basic approach:

This should add HTML-formatted content and show the newly added row.

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
2
  • 5
    My favorite solution: very elegant and with added flexibility to add inner HTML.
    – jimiayler
    Dec 21, 2018 at 16:47
  • 1
    if you have given an id to the tr string then it will remove it so be carfeul.
    – showtime
    Dec 15, 2021 at 9:38
10

I think this script is what exactly you need

var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
2
  • of course you need to modify your new row but i just offered the concept in the answer and left the rest to you :)
    – Marwan
    Aug 20, 2013 at 11:18
  • This has the advantage that you can append a cloned row, and avoid creating a new one, in order to maintain the CSS style. Mar 15 at 21:32
9

You're close. Just add the row to the tbody instead of table:

myTbody.insertRow();

Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.

A live demo is at jsFiddle.

8

let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];

let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);

cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;

row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);

cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
  border-collapse: collapse;
}

td, th {
  border: 1px solid #000;
  padding: 10px;
}
<table id="myTable">
    <thead>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
        </tr>    
     </thead>
    <tbody></tbody>
</table>

6

Add rows:

<html>
    <script>
        function addRow() {
            var table = document.getElementById('myTable');
            //var row = document.getElementById("myTable");
            var x = table.insertRow(0);
            var e = table.rows.length-1;
            var l = table.rows[e].cells.length;
            //x.innerHTML = "&nbsp;";

            for (var c=0, m=l; c < m; c++) {
                table.rows[0].insertCell(c);
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function addColumn() {
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function deleteRow() {
            document.getElementById("myTable").deleteRow(0);
        }

        function deleteColumn() {
            // var row = document.getElementById("myRow");
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].deleteCell(0); // var table handle
            }
        }
    </script>

    <body>
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
            <tr id='myRow'>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </body>
</html>

And cells.

1
  • 8
    I think you should use more sensible variables when creating an example. Mar 20, 2016 at 23:58
4

Add Column, Add Row, Delete Column, Delete Row. Simplest way

    function addColumn(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = row[i].innerHTML + '<td></td>';
      }
    }
    function deleterow(tblId)
    {
        
      var table = document.getElementById(tblId);
      var row = table.getElementsByTagName('tr');
            if(row.length!='1'){
                row[row.length - 1].outerHTML='';
            }
    }
    function deleteColumn(tblId)
    {
        var allRows = document.getElementById(tblId).rows;
        for (var i=0; i<allRows.length; i++) {
            if (allRows[i].cells.length > 1) {
                allRows[i].deleteCell(-1);
            }
        }
    }
    function myFunction(myTable) {
      var table = document.getElementById(myTable);
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].outerHTML;
      table.innerHTML = table.innerHTML + row;
      var row = table.getElementsByTagName('tr');
      var row = row[row.length-1].getElementsByTagName('td');
      for(i=0;i<row.length;i++){
        row[i].innerHTML = '';
      }
    }
    table, td {
      border: 1px solid black;
      border-collapse:collapse;
    }
    td {
      cursor:text;
      padding:10px;
    }
    td:empty:after{
      content:"Type here...";
      color:#cccccc;
    }
   <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form>
    <p>
    <input type="button" value="+Column" onclick="addColumn('tblSample')">
    <input type="button" value="-Column" onclick="deleteColumn('tblSample')">
    <input type="button" value="+Row" onclick="myFunction('tblSample')">
    <input type="button" value="-Row" onclick="deleterow('tblSample')">
    </p>
    <table id="tblSample" contenteditable><tr><td></td></tr></table>
    </form>

    </body>
    </html>

4

You can also use querySelector to select the tbody, then insert a new row at the end of it.

Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.

var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My footer</td>
    </tr>
  </tfoot>
</table>

2

I have tried this, and this is working for me:

var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
3
  • 2
    And what if the footer has 2 rows? Aug 20, 2013 at 12:34
  • 1
    Ok simple make it as var row=table.insertRow(0); it will add row at top Aug 20, 2013 at 12:51
  • @JVerstry tbody: this is exactly what does mozilla
    – Déjà vu
    Aug 28, 2016 at 10:17
2

You can use the following example:

<table id="purches">
    <thead>
        <tr>
            <th>ID</th>
            <th>Transaction Date</th>
            <th>Category</th>
            <th>Transaction Amount</th>
            <th>Offer</th>
        </tr>
    </thead>

    <!--  <tr th:each="person: ${list}"    >
            <td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
            </tr>
    -->

    <tbody id="feedback">
    </tbody>
</table>

JavaScript file:

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/search",
    data: JSON.stringify(search),
    dataType: 'json',
    cache: false,
    timeout: 600000,
    success: function (data) {
        //  var json = "<h4>Ajax Response</h4><pre>"  + JSON.stringify(data, null, 4) + "</pre>";
        // $('#feedback').html(json);
        //
        console.log("SUCCESS: ", data);
        //$("#btn-search").prop("disabled", false);

        for (var i = 0; i < data.length; i++) {
            //$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
            $('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');

            alert(data[i].accountNumber)
        }
    },
    error: function (e) {
        var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
        $('#feedback').html(json);

        console.log("ERROR: ", e);
        $("#btn-search").prop("disabled", false);
    }
});
0
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <title>Expense Tracker</title>
  </head>
  <body>
    <h1>Expense Tracker</h1>

    <div id="myDiv">
      <label for="name">Name:</label>
      <input
        type="text"
        name="myInput"
        id="myInput"
        placeholder="Name of expense"
        size="50"
      /><br /><br />
      <label for="date">Date:</label>
      <input type="date" id="myDate" name="myDate" />
      <label for="amount">Amount:</label>
      <input
        type="text"
        name="myAmount"
        id="myAmount"
        placeholder="Dollar amount ($)"
      /><br /><br />
      <span onclick="addRow()" class="addBtn">Add Expense</span>
    </div>
    <br />
    <input type="button" value="Add Rows" onclick="addRows()" />
    <!-- Optional position -->
    <table id="myTable">
      <tr>
        <th>Name</th>
        <th>Date</th>
        <th>Amount</th>
        <th>Delete</th>
      </tr>
      <tr>
        <td>McDonald's</td>
        <td>6/22/2017</td>
        <td>$12.00</td>
        <td>
          <input type="button" value="Delete" onclick="deleteRow(this)" />
        </td>
      </tr>
    </table>

    <script>
      function deleteRow(r) {
        var i = r.parentNode.parentNode.rowIndex;
        document.getElementById("myTable").deleteRow(i);
      }
      function addRows() {
        console.log("add rows");
        document.getElementById("myTable").innerHTML += `<tr>
        <td>McDonald's</td>
        <td>6/22/2017</td>
        <td>$12.00</td>
        <td>
          <input type="button" value="Delete" onclick="deleteRow(this)" />
        </td>
      </tr>`;
      }
    </script>
  </body>
</html>
0

$("#myTable tbody").append(tablerow);

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Dec 5, 2022 at 2:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.