Undefined "this" in event listener

Ugh. I’m on my second self-driven project and stuck on something. I’m setting up eventListeners on all table cells with the class “available”. The first line of code within the eventListener is working. The second is not, giving me the error “Uncaught TypeError: Cannot read property ‘remove’ of undefined at HTMLTableCellElement.”

Here’s my code:

var spaceAvailable = document.querySelectorAll(".available");

function playableSquares(){
	for(var i = 0; i < spaceAvailable.length; i++){
		spaceAvailable[i].addEventListener("click", function(){
			this.textContent = "X";
			this.ClassList.remove("available");
		});
	};
};

I just don’t understand how “this” clearly points to spaceAvailable[0] for the textContent change, but is suddenly undefined the next line!

Hi, check out this link. It has all the anwsers you need.

For me the simplest solution would be for (let i=0 instead of var if you’re ok with using ES6.

The immediate closure made it angrier. Now the error is:
“Uncaught TypeError: Cannot read property ‘remove’ of undefined
at TicTacToe.js:31
at playableSquares (TicTacToe.js:32)
at clearBoard (TicTacToe.js:102)
at HTMLButtonElement. (TicTacToe.js:84)”

Substituting “let” for “var” had the same error as before.

If I follow the trail on the Stack Overflow to another solution, I change my code to this:

var spaceAvailable = document.querySelectorAll(".available");

function makePlayable(i){
	this.addEventListener("click", function(){
		this.textContent = "X";
		this.ClassList.remove("available");
	});
};

function playableSquares(){
	for(i = 0; i < spaceAvailable.length; i++){
		makePlayable(spaceAvailable[i]);
	};
};

And I get the first error I got, but nine times (one for each of the table cells).

Well, I just had another look and saw you’re using ClassList, I believe it must be classList instead.

YEP. That was exactly it! It’s always one little character somewhere. And that looked wrong to me, too, since it’s not camelcase, but my notes were wrong.

Thanks.

1 Like

Had some more stumbling blocks, but I pushed through and the game is up here if anyone wants to play/waste some time. TicTacToe