<table id="position">
<tr><td>TL</td><td>TC</td><td>TR</td></tr>
<tr><td>CL</td><td>CC</td><td>CR</td></tr>
<tr><td>BL</td><td>BC</td><td>BR</td></tr>
</table>
<script>
document.querySelector("#position td").addEventListener("click", function(){
console.log(this.innerHTML);
});
Trying to get innerHTML of table cell <td>
on click. It returns nothing. When I change selector to #position tr
it returns data, but ONLY for first <tr>
row, when I click on it. When clicking on second, third - returns nothing. Obviously, when I change selector to table #position
it works fine and returns whole table.
I even tried to add class for every cell like <td class="cell">
- document.querySelector(".cell").innerHTML
returns content, but once again - ONLY for first <td>
cell!
How to get clicked td
and why is it behaving so strange? Also, is it possible to get clicked row/column number?
querySelector()
only gives you the first match of the selector,querySelectorAll()
gives you all of them. use the latter and loop over all element to attach the handler. Alternatively, attach a handler to the table as a whole and check the specific target cell. – Jotting