node | element |
function buildTable(data) { var table = document.createElement("table"); var fields = Object.keys(data[0]); console.log(fields); var headRow = document.createElement("tr"); fields.forEach(function(field) { var headCell = document.createElement("th"); headCell.textContent = field; headRow.appendChild(headCell); }); table.appendChild(headRow);
data.forEach(function(object) { var row = document.createElement("tr"); fields.forEach(function(field) { var cell = document.createElement("td"); cell.textContent = object[field]; if (typeof object[field] == "number") cell.style.cssText = "background-color:black;color:white;text-align:right;" row.appendChild(cell); }); table.appendChild(row); });
return table; }
document.body.appendChild(buildTable(PERSON));
| function buildTable(data) { const table = document.createElement("table"), fields = Object.keys(data[0]);
let template = `<tr><th>${fields[0]}</th><th>${fields[1]}</th><th>${fields[2]}</th></tr>`; table.insertAdjacentHTML("afterBegin", template);
for (let { name, age, country } of data) { template = `<tr><td>${name}</td><td>${age}</td><td>${country}</td></tr>`; table.insertAdjacentHTML("beforEEnd", template); } return table; }
document.body.appendChild(buildTable(PERSON));
|
code | code
|
Méthode : map
See the Pen
Dom table for-of by dupont (@dupontcodepen)
on CodePen.
like composant
le code sépare maintenant la logique de construction de l'en-tête et du corps du tableau en deux fonctions distinctes : buildTableHeader
et buildTableBody
.
See the Pen
Dom table function by dupont (@dupontcodepen)
on CodePen.
like react (pas tout à fait)