Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda