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

251
Visualizações
How to hide and display with js

How can I use javascript to toggle a class?

I attempted to colorize clicked-on text by giving the element a class, and that works (the text turns red).

But when I click on the same element twice, the class is not removed. I used toggle class for this but it doesn't seem to work.

const txts = document.querySelectorAll('.txt');

const txtColor = (txt) => {
  txt.addEventListener('click', e => {
    if (e.target.classList.contains('txt')) {
      txts.forEach(txt => txt.classList.remove('red'));
      e.target.classList.toggle('red');
    }
  });
}

txtColor(document.querySelector('ul'));
<ul>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
</ul>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You don't really need the textColor() function, so let's remove that. Then, it might be easier to compose your logic if you move the toggle function into its own function.

One place to be careful is when you are toggling the classes. In your original code, you cannot toggle the same LI off / on / off / on.

Here's why:

First, the code removes the red class from all the LIs (a good strategy) - but then, toggle is used to toggle the clicked LI's class.

Think about that... If the LI is already red, then you remove the class from all LIs (now none of them are red), then you toggle the LI that was already red, it will turn red again - and it looks like nothing happened. But it went red -> nothing -> red very, very fast. Too fast to see it happen.

Therefore, you can first check if the LI already has the red class, and only toggle it if it didn't already have that class.

This structure might help you to see it better.

const txts = document.querySelectorAll('.txt');

txts.forEach((txt) => {
  txt.addEventListener('click', (e) => toggleColor(e));
});

function toggleColor(e){
  const doRed = e.target.classList.contains('red');
  txts.forEach(txt => txt.classList.remove('red'));
  if (!doRed) e.target.classList.toggle('red');
}
.red{
  color: red;
}
li{
  user-select: none;
}
<ul>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
</ul>

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