There is a table 3x3. When you click on any element, it becomes transparent. It turns out to do this by writing onClick = "this.style.opacity = '0';" in each of the nine cells. Help to write a function that does the same thing, but does not lie, but only is called from each cell.
2 answers
Add a class to each cell, for example cell . Then loop up the loop on each cell.
document.querySelectorAll('.cell').forEach(function(cell) { cell.addEventListener('click', function() { cell.style.opacity = '0' }) }) td { background-color: red; } <table style="width:100%"> <tr> <td class="cell">2</td> <td class="cell">3</td> <td class="cell">4</td> </tr> <tr> <td class="cell">4</td> <td class="cell">5</td> <td class="cell">6</td> </tr> <tr> <td class="cell">7</td> <td class="cell">8</td> <td class="cell">9</td> </tr> </table> |
Using the querySelectorAll method to which the css selector is transmitted, find all td. In our case, the table td selector will do.
Then go through the resulting array with a forEach loop, where each element is an ordinal instance of td
Next for each element we add an onclick event (click) at which the opacity properties toogle occur
document.querySelectorAll('table td').forEach(function(obj) { obj.onclick = function() { obj.style.opacity = (obj.style.opacity == 1 || obj.style.opacity == '' ? 0 : 1); } }); td { padding: 10px; } <table border="1"> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> </table> |