Given this 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 code prints out 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>
But I want to assign id for each word so that I can format them dynamicaly
something 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>
So that later on I can have a fuction like this
function formatWord (wordID){
document.getElementById(wordID).style.color ="red";
}
Users can call formatWord (2); formatWord (5);..
randomly
If we can not do this with "td", it doesn’t matter. As long as I can format the words in the table dynamically.
How to add id to each element in this case?
3
Answers
You could pass along the index of the word like so:
We can pass the index value into the array when reducing
You can do it as simple as possible with adding a variable called index and then ++ it on your preferred iteration.
Good Luck!