I have a table, I need to check all the cells one by one, and if it’s somehow not = 0, then paint it in a different color.

Closed due to the fact that off-topic participants Let's say Pie , Dmitry Kozlov , 0xdb , Air , user192664 Oct 27 '18 at 7:03 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- Let's say Pie, Dmitry Kozlov, 0xdb, Air, Community Spirit
If the question can be reformulated according to the rules set out in the certificate , edit it .

    2 answers 2

    function colorCells() { var tbl = document.getElementById("test"); for (var i = 0; i < tbl.rows.length; i++) { for (var j = 0; j < tbl.rows[i].cells.length; j++) { var cell = tbl.rows[i].cells[j]; if (cell.textContent != "0") { cell.classList.add("green"); } } } } /*function colorCells() { var tbl = document.getElementById("test"); [...tbl.rows].forEach( row => { [...row.cells].forEach( cell => { if (cell.textContent != "0") { cell.classList.add("green"); } }) }) }*/ 
     td { width:20px; height:20px; text-align:center; } .green { background:lightgreen; } 
     <table id="test" border="1"> <tr><td></td><td>0</td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td>0</td><td>0</td><td></td><td></td></tr> <tr><td></td><td></td><td>0</td><td></td><td>0</td><td>0</td></tr> <tr><td>0</td><td>0</td><td></td><td></td><td></td><td></td></tr> <tr><td></td><td></td><td>0</td><td></td><td></td><td></td></tr> <tr><td></td><td>0</td><td></td><td>0</td><td>0</td><td></td></tr> </table> <button onclick="colorCells()">Click</button> 

    • what does the cell do? - Zerus Chanel
    • one
      @ZerusChanel Reform your question. - Igor

    Offhand (not all browsers work):

     let cells = document.querySelectorAll('td'); cells.forEach(cell => { if (cell.innerText != '0') cell.style.backgroundColor = 'green' }) 
     <table> <tr> <td>1</td> <td>2</td> <td>0</td> </tr> <tr> <td>0</td> <td>0</td> <td>5</td> </tr> <tr> <td>6</td> <td>0</td> <td>2</td> </tr> </table>