From this code, once you pressed the button, it will generate a new table row with 16 cells. I came up with the ideal ID for each cell, in the pattern of ‘RxCx’, and I’d like to ask everyone what code’s still missing to let it be each cell’s ID?
Thanks a lot for your help!
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
var rowCount = 0;
var cellCount = 0;
btn1.addEventListener('click', () => {
var row = tab.insertRow(-1);
rowCount++;
for (var i = 0; i <= 15; i++) {
row.insertCell(i);
cellCount = i + 1;
var ID = "";
ID = ID + "R" + rowCount + "C" + cellCount;
console.log(ID);
}
});
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
>Solution :
One approach is as follows, with explanatory comments in the JavaScript:
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
let rowCount = 0;
let cellCount = 0;
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
rowCount++;
for (let i = 0; i <= 15; i++) {
// getting a reference to the inserted cell:
let c = row.insertCell(i);
cellCount = i + 1;
let ID = "";
// using += to append the right side of the assignment to the end
// of the existing value:
ID += "R" + rowCount + "C" + cellCount;
// using c.id to update the id property of the c element
// to the value held in the ID variable:
c.id = ID;
}
});
td {
min-block-size: 2em;
min-inline-size: 2em;
}
td[id]::before {
content: attr(id);
}
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
I would probably modify the approach to remove the (unnecessary) counters, and instead make use of the HTMLTableRowElement.rowIndex and HTMLTableCellElement.cellIndex properties of the nodes that you’re already creating:
const tab = document.getElementById("tab");
const btn1 = document.getElementById("btn1");
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
for (let i = 0; i <= 15; i++) {
let c = row.insertCell(i);
// using a template-literal string to concatenate JavaScript
// variables into the string, here we increment the value of
// rowIndex and cellIndex since it seems you want to start
// counting at 1, rather 0 (as JavaScript does by default):
c.id = `R${++row.rowIndex}C${++c.cellIndex}`;
}
});
td {
min-block-size: 2em;
min-inline-size: 2em;
}
td[id]::before {
content: attr(id);
}
<body>
<button id="btn1">Add</button>
<table id="tab"></table>
</body>
References: