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

后端 未结 4 1807
天命终不由人
天命终不由人 2020-12-05 19:07

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

相关标签:
4条回答
  • 2020-12-05 19:18

    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

    0 讨论(0)
  • 2020-12-05 19:22

    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.

    0 讨论(0)
  • 2020-12-05 19:28

    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); 
    
    0 讨论(0)
  • 2020-12-05 19:29

    You can do this:

    var table = document.getElementById('myTableId');
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    
    0 讨论(0)
提交回复
热议问题