I\'m learning JavaScript and recently I have been experimenting with Mouse events, trying to understand how they work.
Instead of using getElementById, we could use .querySelectorAll to retrieve all the table dimensions AKA cells. After which, we can execute a single loop (Although please note that in the back end of JS, there will still be a loop executed to retrieve table cells.). First, let's create the action to be carried out upon clicking a cell:
function tableText() {
alert(this.innerHTML);
}
Let's retrieve all the cells with querySelectorAll method:
var cells = document.querySelectorAll("td")
Place the event listener to each and every cell:
for (var i = 0; i < cells.length; i++)
cells[i].addEventListener("click", tableText)
}
Complete code:
function tableText() {
alert(this.innerHTML);
}
var cells = document.querySelectorAll("td")
for (var i = 0; i < cells.length; i++){
cells[i].addEventListener("click", tableText)
}