1

I am trying to add an add to cart button to each of my items. However when I try to test the <button> to see if its clickable it does not work. I added in the buttons dynamically using javascript, is the addEventListener not working because all of the button will share the same class name? Everything displays exactly how I want it however I'm struggling with the button functionality. I also made sure to put the <script> file at the end of the html file, so that has been ruled out as well.

const createProductCard = (product) => {
  formattedPrice = product.price
    .toString()
    .replace(/\B(?=(\d{3})+(?!\d))/g, ", ");
  return `<div class="column">
    <img src=${product.image} />
    <h2>${product.name}</h2>
    <button class="addToBag" type="button">ADD2BAG</button>
    <p>$ ${formattedPrice}</p>
    </div>`;
};

const createRows = (arr) => {
  let num = 0;
  for (let i = 0; i < arr.length; i++) {
    if (i % 3 === 0) {
      const row = document.createElement("div");
      row.classList.add("row");
      row.id = `row${num}`;
      num += 1;
      productsContainer.appendChild(row);
    }
  }
};
const displayProducts = (arr) => {
  createRows(arr);
  let x = 0;
  const rowClass = document.getElementsByClassName("row");

  for (let i = 0; i < rowClass.length; i++) {
    let row = document.getElementById(`row${i}`);
    for (x; x < arr.length; x++) {
      if (row.childElementCount === 3) {
        break;
      }
      row.innerHTML += createProductCard(arr[x]);
    }
  }
};

In order to test the functionality I tried:

const addToCartBtn = document.querySelector(".addToBag");
addToCartBtn.addEventListener("click", () => {
  console.log("clicked");
})

the console returns this instead of the expected output:

Cannot read properties of null (reading 'addEventListener')

So after some research I tried to add functionality to each button using forEach however when clicking the buttons nothing appears in the console:

const addToBagBtns = document.querySelectorAll(".addToBag").forEach((btn) => {
  btn.addEventListener("click", function() {
    console.log("clicked");
  });
});

I tried console logging the .addToBag class to see why its null and that's when I realized querySelectorAll isn't working at all. All that is returned is an empty node list but getElementsByClassName returns a HTMLCollection.

console.log(document.querySelectorAll(".addToBag"));
// return value
NodeList []
length: 0
console.log(document.getElementsByClassName("addToBag"));
/// return value
HTMLCollection []
0: button.addToBag
1: button.addToBag
2: button.addToBag
3: button.addToBag
4: button.addToBag
5: button.addToBag
6: button.addToBag
7: button.addToBag
8: button.addToBag
length: 9

0 Answers0