I am a beginner. generateTable() is called in the onload() of the body tag. The link is planned to open the api with a parameter. The parameter is a number. In the function getTheadNames() json structure from which I take data to create the table.
function generateTable() {
const jsons = "";
const obj = JSON.parse(jsons);
const tbl = document.createElement("table");
let caption = document.createElement("caption");
caption.textContent = "test";
tbl.appendChild(caption);
const tblHead = document.createElement("thead");
const tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("th");
createPartOfTable(row, cell);
tblHead.appendChild(row);
tbl.appendChild(tblHead);
for (let i = 0; i < obj.length; i++) {
row = document.createElement("tr");
cell = document.createElement("td");
createPartOfTable(row, cell, i, obj);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
tbl.setAttribute("class", "table");
}
function getTheadNames() {
return ["number", "date", "warehouse", "packed", "base", "comment", "total"];
}
function createPartOfTable(row, cell, i = 0, obj = null) {
let names = getTheadNames();
for (let j = 0; j < names.length; j++) {
var nameNode = names[j];
cell = document.createElement(cell.nodeName);
if (cell.nodeName == "TH") var cellText = document.createTextNode(nameNode);
else {
var textNode = obj[i][Object.keys(obj[i])[j] || {}];
if (nameNode == "number") {
const linkText = document.createTextNode(textNode);
const link = document.createElement("a");
link.href = "APIlink?number=" + textNode;
link.appendChild(linkText);
cellText = link;
} else cellText = document.createTextNode(textNode);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
}
Please tell me how I can improve my algorithm and what mistakes I made. I would like the code to be easier to read. Maybe there is a solution in some libraries I don’t know about.
The code itself works and creates a table, example json below
[
{
"number": "000000001",
"date": "2023-11-14T10:26:00",
"warehouse": "test",
"packed": "user",
"base": "",
"comment": "",
"total": 1
},
{
"number": "000000002",
"date": "2023-11-14T10:26:00",
"warehouse": "test",
"packed": "user",
"base": "",
"comment": "test",
"total": 1
}]
2
Answers
table element have specific method you should use : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement
Here is another, template based, way of doing the same job. In the end it is a question of style, which way you actually prefer.