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

90
Vistas
Can't remove body class previosly added with click event

I'm missing something, probably related with bind, but I can not see what and where. I can add a class to a body tag, but I can not remove it latter.

const add_body_class = document.querySelectorAll('.btn-add-class');

add_body_class.forEach(item => {
  item.addEventListener('click', event => {
     document.body.classList.add('foobar');
  })
});

const remove_body_class = document.querySelectorAll('.btn-remove-class');

remove_body_class.forEach(item => {
  item.addEventListener('click', event => {
     // this doesn't work
     document.body.classList.remove('foobar');
     // click event works
     console.log("clicked");
  })
});

BTW I need to use multiple selectors and document.querySelectorAll because of multiple instances, and I can not change any of HTML code.

Any help would be appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It works fine for me, I just wrapped it inside a DOMContentLoaded listener.

<!DOCTYPE html>
<html>

<body>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<button class="btn-add-class">Add</button>
<hr>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
<button class="btn-remove-class">Remove</button>
</body>
<style>
.foobar{
  background-color: yellow;
  }
</style>
<script>
document.addEventListener("DOMContentLoaded", () => {
const add_body_class = document.querySelectorAll('.btn-add-class');

add_body_class.forEach(item => {
  item.addEventListener('click', event => {
     document.body.classList.add('foobar');
     console.log("added");
  })
});

const remove_body_class = document.querySelectorAll('.btn-remove-class');

remove_body_class.forEach(item => {
  item.addEventListener('click', event => {
     // this doesn't work
     document.body.classList.remove('foobar');
     // click event works
     console.log("removed");
  })
});
})
</script>

</html>

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