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

130
Visualizações
using template literals with classlist attribute

javascript newbie here. I'm trying to implement template literals to change the second part of a variable name while calling the toggle method with the classlist attribute. Here's what I have:

bigBoxRight.classList.toggle("turnOff");

and this is what i'm trying to accomplish:

bigBox`${player}`.classList.toggle("turnOff");

Player can be both "Right" or "Left" and it's a string. Is this even possible?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of trying to dynamically create variable names, you should get the element you are trying to toggle the class on first.

Assuming bigBoxRight or bigBoxLeft is the id of the element, you can use your template literals to get the element first:

var elem = document.querySelector(`#bigBox${player}`)

Then you can do:

elem.classList.toggle("turnOff");
about 4 years ago · Juan Pablo Isaza Relatório

0

What I would do is to save another variable that will get the element you need based on your decision and then get the classlist for it

For example

const bigBoxRight = docemnt.querySelector...
const bigBoxLeft = docemnt.querySelector...

const elemRef = true* ? bigBoxRight : bigBoxLeft 

elemRef.classList.toggle("turnOff");

*-  Your logic for when you need the right or the left  bigbox element

Tim's solution might be cleaner if you know when you need the right element or the left

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