I need what if I clicked on a cell in the table it was painted black, the fact is that I somehow managed to achieve that the cells on the red table would be painted, but on the table that is generated after the page loads, for some reason it did not work

var html = '<table><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>', td = document.querySelector("td"); // document.querySelector('td').onclick = function() { // this.style.background = "black"; // }; for (var i = 0; i < td.length; i++) { td[i].onclick = function() { this.style.background = "black"; }; } document.querySelector('#but').onclick = function() { document.querySelector('#new-table').innerHTML = html; }; 
 td { padding: 25px; background: red; cursor: pointer; } #new-table td { background: green; } 
 <button id="but">Создать новую табл</button> <table> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> <div id="new-table"></div> 

    1 answer 1

    After adding the table, you need to add handlers to the new cells, for this you can make the code to add to the function, in the end it can go something like this:

     var html = '<table><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>'; function addHandlers(table) { var tds = table.querySelectorAll("td"); for (var i = 0; i < tds.length; i++) { tds[i].onclick = function() { this.style.background = "black"; }; } } addHandlers(document.querySelector('table')); document.querySelector('#but').onclick = function() { var table = document.querySelector('#new-table') table.innerHTML = html; addHandlers(table); }; 
     td { padding: 25px; background: red; cursor: pointer; } #new-table td { background: green; } 
     <button id="but">Создать новую табл</button> <table> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> <div id="new-table"></div>