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
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
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.
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);
You can do this:
var table = document.getElementById('myTableId');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);