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

169
Visualizações
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 Respostas
Responde à pergunta

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