How to insert row at end of table with HTMLTableElement.insertRow

Background and Setup

I'm trying to create a table from tabular data in javascript, but when I try inserting rows into a table element, it inserts in the opposite order from what I expect and the opposite order of what you get from using appendChild. (Here's a jsfiddle with a live demo of this).

Say I have some data like this:

var data = [
    {"a": 1, "b": 2, "c": 3},
    {"a": 4, "b": 5, "c": 6},
    {"a": 7, "b": 8, "c": 9}
], keys = ["a", "b", "c"];

If I try using the insertRow() and insertCell() methods for creating tables, iterating over the data and keys above. I get the reverse order of what I expect:

Generated by using the following code:

// insert a table into the DOM
var insertTable = insertDiv.appendChild(document.createElement("table")),
    thead = insertTable.createTHead(), // thead element
    thRow = thead.insertRow(), // trow element
    tbody = insertTable.createTBody(); // tbody element


thRow.insertCell().innerText = "#"; // add row header

// insert columns
for (var i = 0, l = keys.length; i < l; i ++) {
    var k = keys[i];
    thRow.insertCell().innerText = k;
}

// insert rows of data
for (var i = 0, l = data.length; i < l; i ++) {
    var rowData = data[i],
        row = tbody.insertRow();
    row.insertCell().innerText = i;
    for (var j = 0, l = keys.length; j < l; j ++) {
        var elem = rowData[keys[j]];
        row.insertCell().innerText = elem;
    }
}

Whereas, if I create a table using document.createElement and appendChild, I get the order I would expect:

Generated by:

// now do the same thing, but using appendChild
var byChildTable = document.createElement("table");
byChildTable.setAttribute("class", "table");
thead = byChildTable.appendChild(document.createElement("thead"));
thRow = thead.appendChild(document.createElement("tr"));

// create table header
thRow.appendChild(document.createElement("td")).innerText = "#";
for (var i = 0, l = keys.length; i < l; i ++) {
    var key = keys[i];
    thRow.appendChild(document.createElement("td")).innerText = key;
}

// insert table data by row
tbody = byChildTable.appendChild(document.createElement("tbody"));
for (var i = 0, l = data.length; i < l; i ++) {
    var rowData = data[i],
        row = tbody.appendChild(document.createElement("tr"));
    row.appendChild(document.createElement("td")).innerText = i;
    for (var j = 0, l = keys.length; j < l; j ++) {
        var elem = rowData[keys[j]];
        row.appendChild(document.createElement("td")).innerText = elem;
    }
}
Question

How do I control the order it puts the elements in the DOM? Is there any way to change this? I guess otherwise I could iterate in reverse order, but even that way, you still can't insert with table.insertRow(). It's just a bummer because the insertRow() and insertCell() methods seem much clearer than table.appendChild(document.createElement("tr")) etc.

The .insertRow and .insertCell methods take an index. In absence of the index, the default value is -1 in most browsers, however some browsers may use 0 or may throw an error, so it's best to provide this explicitly.

To to an append instead, just provide -1, and an append will be done

var row = table.insertRow(-1);
var cell = row.insertCell(-1);

https://developer.mozilla.org/en-US/docs/DOM/table.insertRow

How to insert row at end of table with HTMLTableElement.insertRow , The .insertRow and .insertCell methods take an index. In absence of the index, the default value is -1 in most browsers, however some  Background and Setup. I'm trying to create a table from tabular data in javascript, but when I try inserting rows into a table element, it inserts in the opposite order from what I expect and the opposite order of what you get from using appendChild.

You can do this:

var table = document.getElementById('myTableId');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

HTMLTableRowElement.insertCell(), insertCell() method inserts a new cell (td) into a table row (tr) and returns a reference to the cell This example uses HTMLTableElement. getElementById​(tableID); // Insert a row at the end of the table let newRow = tableRef  If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody> : let specific_tbody = document.getElementById(tbody_id); let row = specific_tbody.insertRow(index)

You have to specify an index in insertCell() like insertCell(inde) in order to work as you expect.

As it is said in www.w3schools.com/jsref

If this parameter is omitted, insertCell() inserts the new cell at the last position in IE and at the first position in Chrome and Safari.

This parameter is required in Firefox and Opera, but optional in Internet Explorer, Chrome and Safari.

An index is required also in inserRow() for the same reason.

HTML DOM Table insertRow() Method, var row = table.insertRow(0); // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element: var cell1 = row.insertCell(0); var cell2 = row. The insertRow () method creates an empty <tr> element and adds it to a table. The insertRow () method inserts the new row (s) at the specified index in the table. Note: A <tr> element must contain one or more <th> or <td> elements. Tip: Use the deleteRow () method to remove a row.

You can do this,

var table = document.getElementById("yourTable");
var row = table.insertRow(-1);

var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3); 

How to add multiple rows and/or columns to a table in the Rich Text , Description. This method creates a new TableRow representing a <tr> tag and inserts it into the table at the specified position. The new row is inserted in the  The value 0 results in the insertion of the new row at the first position whereas -1 can be used to insert the new row at the last position. Below program illustrates the Table insertRow() method : Example-1: Inserting new row at the first position of a table.

How to insert rows and columns in a page using HTML, The preferred technique for inserting a row is to add the row at the end of the rows collection. It is faster to add a row at the end of a table than somewhere in the  Other browsers do not create tBody automatically. On attempt to insert a row to a table without <tbody> section three outcomes are possible: 1) the operation will fail 2) new row is added as direct child of table 3) on the first attempt to insert a row tBody section is created and new row is added as a child if it (namely emulation of IE behavior).

Table.insertRow( ): add a new, empty row to the table, var row = HTMLTableElement.insertRow(optional index = -1);. HTMLTableElement is a reference to a HTML table element. index is the row index of the new row  Table.InsertRows(table as table, offset as number, rows as list) as table About. Returns a table with the list of rows, rows, inserted into the table at the given position, offset. Each column in the row to insert much match the column types of the table. Example 1. Insert the row into the table at position 1.

insertRow · WebPlatform Docs, javascript - Insert a row in a table JQuery - Stack Overflow. javascript insertRow and . javascript - How to insert row at end of table with HTMLTableElement.i. Insert one row into a table. To insert one row into a table, you use the following syntax of the INSERT statement. INSERT INTO table1 (column1, column2,) VALUES (value1, value2,); There are some points that you should pay attention to when you insert a new row into a table: First, the number of values must be the same as the number of

Comments
  • insertRow() Takes an index as an argument so you can choose where to place the newly inserted row. developer.mozilla.org/en-US/docs/DOM/table.insertRow
  • wow - I feel a bit silly about that now - I guess I just missed that on MDN. Thanks all!
  • FYI, some of the methods you're using don't work in Firefox. I think you'll need .appendChild() instead of .createTBody() and .createTHead(). Also, Firefox will throw an error if you don't include the index in the insertCell() and .insertRow().
  • @amnotiam thanks, good to know. Apparently the appendChild method is faster too.
  • @JeffTratner: You're welcome. Also, Firefox doesn't honor the non-standard .innerText. The standard property is .textContent. IE8 and lower need .innerText, so if you support those browsers, I would make a variable like this at the top of your application: var text = ("textContent" in document) ? "textContent" : "innerText";, and then use it to get and set text. row.insertCell(-1)[text] = k; Here's a full working version: jsfiddle.net/ZfqRu
  • @vortex7: FYI, to highlight documentation, use the blockquote formatting instead of the code formatting.