Quick help with project

Good evening all! I’m trying my hand at a x’s and o’s game. I’m stuck on the click logic. Here’s what I have.

let playerOne = true;
let box = document.querySelectorAll(":scope .box");

box.addEventListener(“click”, function() {
if (playerOne) {
box.textContent = “X”;
playerOne = false;
} else {
box.textContent = “O”;
playerOne = true;
}
});

My guess is that the .querySelectorAll isn’t functioning as I would expect it too. I’m trying to use it to select 9 .box classes in my html file.

Thank you!

Hi,

querySelectorAll() selects ALL those boxes. You’re not targeting one of them alone for each event.

Happy coding!

Thank you! thats good to know. I’m guessing a the .addEventListener can be used inside a for loop … that would go through each of the array items?

Yes. Don’t forget to check on MDN, Stackoverflow… to try to solve your problems, that will make you a better developer.

Also keep in mind you can alternately, given in this case we have a small subset (only 9) options, create the divs as id ‘box1’, ‘box2’, ‘box3’-- Or ‘box00’ , ‘box01’, ‘box02’, and then when you are in JS concatenate on the present selector (i.e. say a double for loop of x and y, size three by three and each selector you concat the name).

This might save you some JS code being able to repeat the operation, but it is just an idea. There are many ways to go about solving this problem.

Thanks for all the help! I’m trying to figure out how to iterate over it with a for loop, but am getting stuck! I know I need to find a way to select the individual objects and associate the eventListener to it.

for (i = 0; i < 9; i++) {
let buttonClick = [];
if (playerOne) {
this.addEventListener(“click”, function() {
this.textContent = “x”;
playerOne = false;
})};

This is what I’ve tried, and the farthest Ive gotten, but I know I’m doing something wrong. Any tips to get me on the right track … without making the solution a gimme? I need to figure this out myself :slight_smile:

Thanks all!

Alright! Thank you for the help … one more question popped up. I’ve created 9 empty boxes, that I’ve styled, however no matter what I do with the padding/margin … whenever a user clicks into the box, and an X or O gets placed, the box size adjusts. Any help would be appreciated!