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

119
Views
Adding clickeventlistener to all children of a particular class using addEventListener

I am making a card like this: enter image description here

The expected behaviour is that when I click any of the rating circles, their color should change to grey for which I have a class defined in my css that I toggle using js code.

The codepen for my solution is this. Using the js code that I have written, whenever I click any of the ratings, the last one turns grey all the time.

This is my current code:

// getting the objects
const submitBtn = document.querySelector('button');
const ratingsParent = document.querySelector('.ratings');

console.log(ratingsParent.children);

// sanity check
submitBtn.addEventListener('click', () => {
    console.log('Clicked');
})

for (var r of ratingsParent.children) {
    r.addEventListener('click', ()=> {
        r.classList.toggle('clicked');
    })
}

But when I change r.ClassList.toggle to evt.target.ClassList.toggle, it shows the expected behaviour. Im extremely new to JS and just starting to learn frontend dev so Im unable to figure out the reason for this behaviour.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

var has different behaviour than let and const when declared in a loop header – it only creates a single variable for the entire loop, which all closures share. You clearly have support for let and const, so you should literally never use var. (Maybe there’s a linting rule you can enable?)

for (const r of ratingsParent.children) {
    r.addEventListener('click', ()=> {
        r.classList.toggle('clicked');
    });
}

There’s also the option of attaching a single listener to the parent and letting events bubble up, note.

ratingsParent.addEventListener('click', e => {
    if (e.target.parentNode === ratingsParent) {
        e.target.classList.toggle('clicked');
    }
});
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!