Home > other >  Add querySelectorAll to add a class to a button
Add querySelectorAll to add a class to a button

Time:05-27

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.

CodePudding user response:

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");
}

CodePudding user response:

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");
}

  • Related