Trying to change the background of a specific button when clicking on it is proving to be quite the challenge for me. I created an array of 100 buttons (with the intention of developing a simple game later) using a for loop, giving each button a unique id and function call based on the 'i' value incrementing in the loop. However, I am encountering an error instead of successfully changing the background upon clicking, which reads: "Uncaught TypeError: Cannot read property 'setAttribute' of null at showOptions (brain.js:31) at HTMLButtonElement.onclick (index.html:15)"
The code snippet looks something like this:
var btn = [];
function generateBoard() {
for (i = 0; i < 100; i++) {
var modulo = i % 10;
var up, forLeft;
btn[i] = document.createElement("BUTTON");
var element = document.getElementById("body");
//btn[i].innerText = "CLICK ME";
element.appendChild(btn[i]);
btn[i].style.backgroundColor = "white";
btn[i].id = i;
btn[i].style.width = "50px";
btn[i].style.height = "40px";
btn[i].style.position = "absolute";
btn[i].style.top = modulo * 100;
btn[i].style.left = Math.floor(i / 10) * 100;
btn[i].x = (i + 10) % 10;
btn[i].y = Math.floor(i / 10);
document
.getElementById(btn[i].id)
.setAttribute("onclick", "showOptions(i)");
btn[i].innerText = btn[i].id;
console.log(
btn[i].id +
" " +
btn[i].style.left +
" " +
btn[i].style.top +
" " +
btn[i].x +
" " +
btn[i].y
);
}
}
generateBoard();
function showOptions(i) {
document.getElementById(i).setAttribute("style", "background-color: red;"); //this is line 31
}
In the console log, I can see that btn[i].id shows the correct digit, surprisingly.
The error line (index.html:15) simply points to
</html>