[javascript] How to insert a row in an HTML table body in JavaScript

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?

This question is related to javascript html html-table insert row

The answer is


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

_x000D_
_x000D_
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);
_x000D_
<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>
_x000D_
_x000D_
_x000D_

(old demo on JSFiddle)


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);

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

_x000D_
_x000D_
    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 = '';
      }
    }
_x000D_
    table, td {
      border: 1px solid black;
      border-collapse:collapse;
    }
    td {
      cursor:text;
      padding:10px;
    }
    td:empty:after{
      content:"Type here...";
      color:#cccccc;
    }
_x000D_
   <!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>
_x000D_
_x000D_
_x000D_


Add rows:

_x000D_
_x000D_
<html>_x000D_
    <script>_x000D_
        function addRow() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            //var row = document.getElementById("myTable");_x000D_
            var x = table.insertRow(0);_x000D_
            var e = table.rows.length-1;_x000D_
            var l = table.rows[e].cells.length;_x000D_
            //x.innerHTML = "&nbsp;";_x000D_
_x000D_
            for (var c=0, m=l; c < m; c++) {_x000D_
                table.rows[0].insertCell(c);_x000D_
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function addColumn() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].insertCell(0);_x000D_
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function deleteRow() {_x000D_
            document.getElementById("myTable").deleteRow(0);_x000D_
        }_x000D_
_x000D_
        function deleteColumn() {_x000D_
            // var row = document.getElementById("myRow");_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].deleteCell(0); // var table handle_x000D_
            }_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
    <body>_x000D_
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>_x000D_
_x000D_
        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>_x000D_
            <tr id='myRow'>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

And cells.


You can try the following snippet using jQuery:

$(table).find('tbody').append("<tr><td>aaaa</td></tr>");

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;

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);
    }
});

I think this script is what exactly you need

var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?

Examples related to insert

How to insert current datetime in postgresql insert query How to add element in Python to the end of list using list.insert? Python pandas insert list into a cell Field 'id' doesn't have a default value? Insert a row to pandas dataframe Insert at first position of a list in Python How can INSERT INTO a table 300 times within a loop in SQL? How to refresh or show immediately in datagridview after inserting? Insert node at a certain position in a linked list C++ select from one table, insert into another table oracle sql query

Examples related to row

Python Pandas Replacing Header with Top Row Return row number(s) for a particular value in a column in a dataframe How to insert a row in an HTML table body in JavaScript Referencing Row Number in R Python pandas: fill a dataframe row by row MS SQL 2008 - get all table names and their row counts in a DB How do I delete rows in a data frame? Remove table row after clicking table row delete button Javascript get the text value of a column from a particular row of an html table How to add a new row to datagridview programmatically