<table> 提供專屬集合屬性,比通用 childNodes 更語意化、更可靠:
table.rows:所有 <tr>(包含 thead/tbody/tfoot 內)row.cells:該列所有 <td>/<th>const table = document.getElementById("dataTable");
for (let i = 0; i < table.rows.length; i++) {
const row = table.rows[i];
for (let j = 0; j < row.cells.length; j++) {
const cell = row.cells[j];
console.log(`Row ${i}, Col ${j}:`, cell.textContent);
// 寫入範例
cell.textContent = `R${i}C${j}`;
}
}
// 只抓 tbody 內的 td,避開表頭
const cells = document.querySelectorAll("#dataTable tbody td");
cells.forEach((cell, idx) => {
const rowIdx = Math.floor(idx / 4); // 假設 4 欄
const colIdx = idx % 4;
cell.textContent = `R${rowIdx}C${colIdx}`;
});
// 獲取第 3 行(索引 2)
const thirdRow = table.rows[2];
thirdRow.cells[1].style.background = "yellow";
// 獲取第 2 列所有儲存格
for (const row of table.rows) {
row.cells[1].classList.add("highlight-col");
}
原文第二種用 childNodes 的寫法有嚴重問題:
childNodes 包含**文字節點**(換行縮排),導致索引錯位。getElementByIdx 非標準方法(應為 getElementById)。j < tr.childNodes[j].length 邏輯錯誤。修正版:
const table = document.getElementById("mylist");
let msg = "";
for (const row of table.rows) { // 直接用 rows 集合
for (const cell of row.cells) {
msg += cell.textContent + " | ";
}
}
console.log(msg);
// 新增一列到末尾
const newRow = table.insertRow();
["張三", "25", "工程師"].forEach(text => {
const cell = newRow.insertCell();
cell.textContent = text;
});
// 刪除第 2 列(索引 1)
if (table.rows.length > 1) table.deleteRow(1);