'Javascript onclick function, how to get it to repeat?

var table = document.querySelectorAll(".validcell")[0];
if (table) table.onclick = function (e) {
    var target = (e || window.event).target;
    if (target.tagName in { TD: 1, TH: 1 })
        target.setAttribute('style', 'background-color: #F00');
    setInterval(table, 50);
};

Trying to get this function to repeat whenever a cell on 10/10 table is clicked. Seems to stop after 1 cell, top left corner is selected. Any ideas?



Solution 1:[1]

var table = document.querySelectorAll(".validcell");
       
table.forEach(cell => cell.onclick = onclickHandler)

function onclickHandler(e) { 

  var target = e.target;

    if (target.tagName in { TD: 1, TH: 1 })
    {
      target.setAttribute('style', 'background-color: #F00');
    }
    
};
td, th{
  padding:5px;
  border:1px solid black
}
<table>
  <tr>
    <th class="validcell">Header1</th>
    <th class="validcell">Header2</th>
    <th class="validcell">Header3</th>
   <tr>
   <tr>
    <td class="validcell">Dummy Text</td>
    <td class="validcell">Dummy Text</td>
    <td class="validcell">Dummy Text</td>
   <tr>
</table>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Salwa A. Soliman