I want to write a code in JavaScript, which will get Id of an element(in my case clicking on table. each <td> has it own id), and than using this ID I want to access corresponding element in Array. So many tries but with no success. Below is my code, please help me understand what I am doing wrong. what i can do to fix it ? :(
const items = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],[1, 4, 7],[2, 5, 8]];
let cells = document.querySelectorAll(".cell");
function findIndex() {
let index;
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function (e) {
index = Number(e.target.id);
});
}
return index;
}
console.log(items[findIndex()]);
You wrote the listener for click. Function inside the eventListener will be called only after you click on the specific table cell. Below I posted the example where after clicking I access and log into the console a corresponding value from the array.
So this is how you should access your value items[Number(event.target.id)] and pay attention that it'll be executed only after your click on the cell.
const items = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
];
document.querySelectorAll('.cell').forEach((currentElement) => {
currentElement.addEventListener("click", function(event) {
console.log(items[Number(event.target.id)]);
})
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Solution</title>
</head>
<body>
<table>
<tr>
<td id="0" class="cell">Row 1</td>
<td id="1" class="cell">Row 2</td>
<td id="2" class="cell">Row 3</td>
</tr>
<tr>
<td id="3" class="cell">Row 4</td>
<td id="4" class="cell">Row 5</td>
<td id="5" class="cell">Row 6</td>
</tr>
</table>
</body>
</html>