Reputation: 21
I'm a beginner working on a simple Tic Tac Toe game in Java Script. Each of the game fields is defined in the "fields" array. I want to have a "for" loop to change the value in the field to "X" on click.
Here is the code that I'm using, which gives me the following error message: Uncaught TypeError: Cannot set property 'textContent' of undefined at HTMLTableCellElement.fields..onclick . The console log works just fine.
for(var b=0; b < fields.length; b++){
fields[b].onclick = function(){
console.log("content changed")
fields[b].textContent= 'X'}
};
I don't understand why this is not working, while this works exactly as expected and changes the value of every cell to "g":
for(var b=0; b < fields.length; b++){
fields[b].textContent ="g"
};
And when I use one field from the array, it also works just fine.
fields[3].onclick = function(){
console.log("content changed")
fields[3].textContent= 'X'}
Why is my code giving me the error message?
Upvotes: 2
Views: 57
Reputation: 1431
Your index b
is resolved to the value at the end of the loop when it tries set the eventlistener and textContent.
Try "let" instead of "var" (works for me with let).
for(let b=0; b < fields.length; b++)
Upvotes: 1