Sunday, November 16, 2025

Web: HTML DOM API: tables

HTMLTableElement - Web APIs | MDN

The HTMLTableElement interface provides special properties and methods (beyond the regular HTMLElement object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an HTML document.

 Abandonware of the web: do you know that there is an HTML tables API? | Christian Heilmann

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>

// 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';

// here is "default alternative"... not much different... and simpler than React :)
table.forEach((row) => {
  let r = document.createElement('tr');
  t.appendChild(r);
  row.forEach((l) => {
    let c = document.createElement('td');
    c.innerText = l;
    r.appendChild(c);
  })
});


No comments: