I\'m learning JavaScript and recently I have been experimenting with Mouse events, trying to understand how they work.
var table = document.getElementById("tableID");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
is an example of what you could do. DEMO
Just insert onclick
into each <td>
of the table and if the cell's name were example, you could do something similar to this:
<td onclick="alert('You are clicking on the cell EXAMPLE')">
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)
}