i have a problem with table
<td id="1" onclick="func1()">1</td>
<td id="2" onclick="func1()">2</td>
<td id="3">3</td> <td id="4">4</td>
<td id="5">5</td>
and i want to change color in one cell without give another id to cell and type x5 this same function to another cell, okay, this is a js code:
function func1() {
let table = document.querySelector("td");
alert("pole" + table + "nacisniete");
table.style.backgroundColor = "grey";
}
if i clicked cell 2, cell1 change color, i want to have 1 function and this must change a color in selected cell
Sorry for my english, im form poland
i want to write another id to another cell and i must have a 25 functions for this work, so i pick queryselector to pick a one cell but this dont work, i picked cell2 and change color to cell1
2
Answers
Instead of using a function on each TD, I’m using document.querySelectorALL to loop through the TDs and give each an event listener. Also, I’m adding a class instead of changing it in javascript as this will give you more options down the road. I commented out two lines these lines will remove the background on a td that has already been clicked so only one can be clicked at a time. You don’t need that but I wasn’t sure if that was what you wanted or not.
Add event listener to the parent element: "myTable" and use event.target to add class to the currently clicked cell