insertRow 是新增表格列最直觀的方法。它會建立一個 tr 並掛到指定位置,回傳該列元素,讓你可以立刻往里塞儲存格。
<!DOCTYPE html>
<html>
<head>
<script>
function insRow() {
var x = document.getElementById('myTable').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = "NEW CELL1";
z.innerHTML = "NEW CELL2";
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr><td>Row1 cell1</td><td>Row1 cell2</td></tr>
<tr><td>Row2 cell1</td><td>Row2 cell2</td></tr>
<tr><td>Row3 cell1</td><td>Row3 cell2</td></tr>
</table>
<br>
<input type="button" onclick="insRow()" value="Insert row" />
</body>
</html>語法為 table.insertRow(index):
· index 是相對於 table 的 rows 集合,0 為最前面。
· 傳入 -1 或省略時,會附加到最後。
· 回傳新建立的 HTMLTableRowElement。
範例傳入 0,所以新列會出現在最上方。若你想加在尾端,寫 insertRow(-1) 即可。
這裡有個實務上非常常踩的坑:table.rows 包含 thead、tbody、tfoot 的所有列,索引是跨區段連續計算的。如果你的表格有固定的標題列包在 thead 裡,那麼 insertRow(0) 會把新列插到標題列之前,視覺上就跑到表頭上面去了。
// 正確做法:明確指定要插入的 tbody
var tbody = document.querySelector('#myTable tbody');
var row = tbody.insertRow(-1); // 加在資料列最後
row.insertCell(0).textContent = "NEW CELL1";
row.insertCell(1).textContent = "NEW CELL2";另外,如果表格用了 <thead> 且其後有 <tbody>,直接在 table 上呼叫 insertRow 時,瀏覽器會自動把新列放進第一個 tbody——但與其依賴這個行為,不如明確選定目標區段。
迴圈中連續 insertRow 會觸發多次 DOM 更新。資料量大時,建議先在 DocumentFragment 中組裝,最後一次掛上:
var tbody = document.querySelector('#myTable tbody');
var frag = document.createDocumentFragment();
data.forEach(function(item) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + item.a + '</td><td>' + item.b + '</td>';
frag.appendChild(tr);
});
tbody.appendChild(frag);不過若資料含有外部輸入,仍應改用 createElement 加 textContent 組裝,避免 innerHTML 帶來 injection 風險。