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

118
Vistas
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 Respuestas
Responde la pregunta

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