I want to create a table and number it from the top left to the buttom right. So far I have this code:
function generateTable() {
const tbl = document.createElement("table"); // Creates the table element
const tblBody = document.createElement("tbody"); // Creates the table body element
// creating all cells
for (let i = 0; i < 2; i++) {
// creates a table row
const row = document.createElement("tr");
for (let j = 0; j < 2; j++) {
const cell = document.createElement("td");
row.appendChild(cell);
}
tblBody.appendChild(row);
}
for (var k = 0, cell; cell = tbl.cells[k]; k++)
{
const cellText = document.createTextNode(`cell nr. ${k}`); // The cell should be numbered 'k'
cell.appendChild(cellText); // Puts the cellText into the cell
}
tbl.appendChild(tblBody); // Puts the table body into the table
document.body.appendChild(tbl); // Puts the talbe into the document body
tbl.setAttribute("border", "2");
}
However, at the for loop that’s meant to iterate through the cells
for (var k = 0, cell; cell = tbl.cells[k]; k++)
{
const cellText = document.createTextNode(`cell nr. ${k}`);
cell.appendChild(cellText);
}
I get the error
Uncaught TypeError: Cannot read properties of undefined (reading '0')
What does that error mean? I am quite sure that at this point in the code the table is already created, or not?
2
Answers
The issue is due to your use of
tbl.cells[k]
– a HTML TableElement does not have acells
property.You can fix your issue, and remove the need for 2 separate loops, by setting the text of the cell as you create it:
As a side note, the
border
attribute of the<table>
element is deprecated and should not be used. Use CSS to style the table instead.you would be wiser to use the JS methods specifically related to tables…
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement
(and the use of css is also preferable…)