网页的废弃技术:你知道HTML表格API的存在吗?
Do you know that there is an HTML tables API?

原始链接: https://christianheilmann.com/2025/10/08/abandonware-of-the-web-do-you-know-that-there-is-an-html-tables-api/

## JavaScript 中被遗忘的表格 API 在 JavaScript 中创建 HTML 表格时,开发者常常使用 `innerHTML` 进行字符串操作——这种做法容易产生安全风险。然而,存在一个鲜为人知的原生 API,可以直接操作表格元素。 该 API 允许程序化地创建表格、行、单元格 (TD)、页眉(尽管目前只能直接创建 TD 单元格)、页脚和标题。它避免了每次更改时重新渲染整个表格,从而提高了效率。 使用 `insertRow()` 和 `insertCell()` 等方法,您可以从数据数组构建表格,并通过索引访问单个单元格(例如 `t.rows[1].cells[1]`)。可以使用 `insertRow(-1)` 将行添加到末尾。 虽然有些古怪——例如使用 `-1` 进行追加——但此 API 提供了一个机会。作者建议通过添加事件和改进元素创建等功能来增强它,将表格从简单的布局工具提升为 Web 环境中的真正数据结构。

相关文章

原文

The demo code further down as an image

When people turn data into HTML tables using JavaScript, they either use the DOM methods (createElement() and the likes), but most of the time just append a huge string and use innerHTML, which always is a security concern. However, did you know that HTML tables also have an old, forgotten API ? Using this one, you can loop over tables, create bodies, rows, cells, heads, footers, captions an summaries (yes, HTML tables have all of those) and access the table cells. Without having to re-render the whole table on each change. Check out the Codepen to see how you can create a table from a nested array:

let table = [
  ['one','two','three'],
  ['four','five','six']
];
let b = document.body;
let t = document.createElement('table');
b.appendChild(t);
table.forEach((row,ri) => {
  let r = t.insertRow(ri);
  row.forEach((l,i) => {
    let c = r.insertCell(i);
    c.innerText = l;  
  })
});

let table = [ ['one','two','three'], ['four','five','six'] ]; let b = document.body; let t = document.createElement('table'); b.appendChild(t); table.forEach((row,ri) => { let r = t.insertRow(ri); row.forEach((l,i) => { let c = r.insertCell(i); c.innerText = l; }) });

You can then access each table cell with an index (with t being a reference to the table):

console.log(t.rows[1].cells[1]);
// => <td>five</td>

console.log(t.rows[1].cells[1]); // => <td>five</td>

You can also delete and create cells and rows, if you want to add a row to the end of the table with a cell, all you need to do is:

t.insertRow(-1);
t.rows[2].insertCell(0);
t.rows[2].cells[0].innerText = 'foo';

t.insertRow(-1); t.rows[2].insertCell(0); t.rows[2].cells[0].innerText = 'foo';

There are a few things here that are odd – adding a -1 to add a row at the end for example – and there seems to be no way to create a TH element instead of a TD. All table cells are just cells.

However, seeing how much of a pain it is to create tables, it would be fun to re-visit this API and add more functionality to it. We did add a lot of things to HTML forms, like formData and the change event, so why not add events and other features to tables. That way they’d finally get the status as data structures and not a hack to layout content on the web.

联系我们 contact @ memedata.com