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

172
Vistas
Use addEventListener() to access multiple objects

I want my checkboxes's label to highlight when on and off (like a IRL switch) and I'm not figuring out how to reach all of them without having to make a listener for each of them (I belive there must be some way)

Checkboxes be like:

<label id="labeltest"><input id="checkboxtest" type="checkbox" name="diet" value="Egg" hidden/>Egg</label>

JS be like:

var labeltest = document.getElementById("labeltest")

labeltest.addEventListener("click", function () {
    if (this.firstChild.checked) {
        this.classList.remove("unchecked")
        this.classList.add("checked")
    } else if (this.firstChild.checked === false) {
        this.classList.remove("checked")
        this.classList.add("unchecked")
    }
});

I've tried with class instead of ID but didn't work

Also tried something like this with classes to make labeltest an array:

labeltest.forEach(element => {
    element.addEventListener("click", function () {
    (FUNCTION HERE)
});

But didn't work either

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

0

You don't need any JavaScript to accomplish this.

If you reorder your input and labels like this:

<input id="diet-egg" type="checkbox" name="diet" value="Egg" hidden/>
<label for="diet-egg">Egg</label>

Important: Be sure that the for attribute value matches the id of the input the label is connected to. This enables checking and unchecking the checkbox by clicking the <label> element.

Then you can use the adjacent sibling selector + to define the styles of the label whenever the input is checked and unchecked.

input + label {
  /* unchecked label styles */
}

input:checked + label {
  /* checked label styles */
}
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