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

73
Visualizações
Check class existence after clicking an element

I'm trying to brush up my javascript and have a simple setup of html, CSS and JS connected.

The console.log prints out Clicked so I know it's working, but my code is wrong and I can't see it. The element is not checking for the existing class 'red'.

I'd like to check if the class red is there, and if it is then remove it and if its not, then add the class.

Can any of you point me in a direction?

TIA

tekst.addEventListener("click", () => {
  console.log("Clicked");
  tekst.classList.add("red");

  if (tekst.classList.contains("")) {
    tekst.classList.add("red");
  } else if (tekst.classList.contains("red")) {
    tekst.classList.remove("red");
  }
});
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Your code works. But you're adding red and then immediately removing it so you won't see a change.

The alternative to the conditional is to just toggle the class instead. (I've added a timeout so you can see this working).

const tekst = document.querySelector('.tekst');

// Comment this line out to see the reverse effect
tekst.classList.add("red");
setTimeout(() => tekst.classList.toggle('red'), 2000);
.red { color: red; }
<div class="tekst">Test</div>

about 4 years ago · Santiago Gelvez Relatório

0

In my point of view, you just need to use toggle method like so:

  tekst.classList.toggle("red");

about 4 years ago · Santiago Gelvez 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