Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!