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

204
Vistas
Add querySelectorAll to add a class to a button

I'm having difficulty with using Javascript to add a class to a button.

Context: I have multiple cards in an instragram type format with a post and a "like" button. I want to add a class of card__like-button which changes the image to a filled heart but i remembered that querySelector only applies to the first element, instead i tried using querySelectorAll but now the code doesn't apply to anything.

First attemp:

// Controls for active like button
let likeButton = document.querySelector(".card__like-button");
   
// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);
    
// Add class on button click
function likeButtonClick() {
likeButton.classList.toggle("card__like-button_active");
    }

Second attemp

// Controls for active like button
let likeButton = document.querySelectorAll(".card__like-button");

// Event listener for like button click
likeButton.addEventListener("click", likeButtonClick);

// Add class on button click
function likeButtonClick() {
  likeButton.classList.toggle("card__like-button_active");
}

I created the following codepen to replicate the problem.

I've search on the site, w3schools documentation, etc. and can't seem to find what am I doing wrong.

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

0

Because of the document.querySelectorAll method will return an array of NodeList details see here, you cannot directly assign the addEventListener event to a list.
Instead, you have to loop through each element and assign events to it

document.querySelectorAll(".card__like-button").forEach(ele => {
    ele.addEventListener("click", likeButtonClick);
});

// Add class on button click
function likeButtonClick() {
  this.classList.toggle("card__like-button_active");
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try it :

let likeButtons = document.querySelectorAll(".card__like-button");
Array.from(likeButtons).forEach(ele => {
    ele.addEventListener("click", likeButtonClick);
});
// Add class on button click
function likeButtonClick() {
  this.classList.toggle("card__like-button_active");
}

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