Search code examples
javascripthtmlcss

How to add id to each element in this case?


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?


Solution

  • Another (imho more simple) way to create the table, without innerHTML

    arr2tbl( 
      ['ac', 'bd', 'bf', 'uy', 'ca'], 
      document.querySelector(`#wordTable`), 
      2 );
    
    document.querySelector(`pre`).textContent = 
      document.querySelector(`#wordTable`).outerHTML;
    
    function arr2tbl(words, forTable, ncols) {
      let currentRow = document.createElement(`tr`);
      forTable.append(currentRow);
      
      words.forEach( (word, i) => {
         if (i > 0 && i % ncols === 0) {
            forTable.append(currentRow.cloneNode());
         }
         
         forTable.querySelector(`tr:last-child`).append(
          Object.assign( document.createElement(`td`), 
          { id: i + 1, textContent: word } ) );
      });
    }
    <table id="wordTable"></table>
    <h3>The table html</h3>
    <pre></pre>