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

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

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 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