Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Having trouble adding class to a div whilst building Tic Tac Toe game

I've looped through the divs and added event listeners to each of them. I'm now trying to add a class to the div when its clicked. I can successfuly add the class if i target the tile by ID but I want to add the class to the tile that is clicked.

var gameBoard = document.getElementsByClassName("tile")
var playerOne = {
"turn": true,
"class": "cross" 
}

var playerTwo = {
"turn": false,
"class": "naught" 
}
for (let i = 0; i < gameBoard.length; i++ ) {
gameBoard[i].addEventListener("click", takeTurn)
}


function takeTurn () {
this.classList.add(playerOne.class)
}

If I store a tile in a variable using getElementById then use

tileOne.classList.add(playerOne.class)

it works fine. but every div clicked would just change tile ones class and not the targeted click.

I'm still fairly new to programming so I think I'm missing something. Can anyone help?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When you add a listener you receive event data as arguments in the function called. So, you have to change your function takeTurn with:

function takeTurn (event) {
    event.target.classList.add(playerOne.class)
}

event.target select the element that trigger the event.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!