Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda