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

122
Vistas
classList.toggle() not adding the class

I'm trying to make a switch change the background color of a div using classList.toggle, but it isn't working and I don't know why, even though it's probably very simple. Can someone clarify this to me, please?

var toggle = document.getElementById('switch')

toggle.onclick = function() {
  document.getElementById('testDiv').classList.toggle('test')
}
#testDiv {
  width: 250px;
  margin: auto;
  margin-top: 16px;
  background-color: white;
}

.test {
  background-color: black !important;
}
<label class="switch" id="switch" onclick="myFunction()">
  <input type="checkbox">
  <span class="slider round"></span>
</label>

<div id="testDiv">
  <p>
    plain text
  </p>
</div>

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

0

You can call the myFunction when the user clicks the checkbox. Fixed the CSS file to place !important in proper position.

function myFunction(){
    document.getElementById('testDiv').classList.toggle('test');
}
#testDiv {
  width: 250px;
  margin: auto;
  margin-top: 16px;
  background-color: white;
}

.test {
  background-color: black !important;
  color: white;
}
<label class="switch" id="switch" for="change_bg">Change background</label>
<input type="checkbox" id="change_bg" onclick="myFunction()">

<div id="testDiv">
  <p>
    plain text
  </p>
</div>

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