Files
uni-web-site/labs/lab1/JavaScript/table.js
2026-02-27 11:00:27 +10:00

51 lines
1.4 KiB
JavaScript

const createTable = (data, idTable) => {
const table = document.getElementById(idTable);
if (data.length == 0) {
return;
}
const header = Object.keys(data[0]);
/* создание шапки таблицы */
if (!table.firstElementChild) {
const headerRow = createHeaderRow(header);
table.append(headerRow);
}
/* создание тела таблицы */
const bodyRows = createBodyRows(data);
table.append(bodyRows);
};
const clearTable = (idTable) => {
const table = document.getElementById(idTable);
if (table.children.length > 1) {
table.removeChild(table.children[1]);
}
}
const createHeaderRow = (headers) => {
const tr = document.createElement('tr');
headers.forEach(header => {
const th = document.createElement('th');
th.innerHTML = header;
tr.append(th);
});
const thead = document.createElement('thead')
thead.appendChild(tr)
return thead;
};
const createBodyRows = (rows) => {
const body = document.createElement('tbody');
rows.forEach(row => {
const rowElement = document.createElement('tr');
for (let key in row) {
const td = document.createElement('td');
td.innerHTML = row[key];
rowElement.appendChild(td);
}
body.appendChild(rowElement);
})
return body;
}