Here is the given code:
var words = ['ac', 'bd', 'bf', 'uy', 'ca'];
document.getElementById("wordTable").innerHTML = arr2tbl(2);
function arr2tbl(ncols) {
return words.reduce((a, c, i) => {
if (i % ncols == 0) a.push([]);
a.at(-1).push(c);
return a;
}, []).map(r => "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>").join("\n");
}
<table id="wordTable"></table>
The above code generates this table:
<table>
<tr>
<td>ac</td> <td>bd</td>
</tr>
<tr>
<td>bf</td> <td>uy</td>
</tr>
<tr>
<td>ca</td><td></td>
</tr>
</table>
I need to assign an id for each word so I can style them dynamically. The desired formatting should look like this:
<table>
<tr>
<td id="1">ac</td> <td id="2">bd</td>
</tr>
<tr>
<td id="3">bf</td> <td id="4">uy</td>
</tr>
<tr>
<td id="5">ca</td><td></td>
</tr>
</table>
To enable flexible styling with a function like this:
function formatWord(wordID){
document.getElementById(wordID).style.color = "red";
}
Users can randomly call formatWord(2); formatWord(5);..
.
If assigning ids to "td" elements is not possible, it doesn't matter as long as we can apply dynamic styles to the words in the table.
How can I add an id to each element in this scenario?