1

I am working on an e commerce website where I had to generate the html from javacript but also creating data. But the buttons are not working with the addEventListeners. It just wouldnt do anything even after i click on them.

    `<div class="product-container">
            <div class="product-image-con">
                <img class="product-img" src="${bread.image}" alt="bread">
            </div>

            <div class="product-price">
                $${bread.price}
            </div>

            <div class="product-name">
              ${bread.name}
            </div>

            <div class="sub-side">
                
            <div class="product-insight">
                <i class='bx bx-info-circle' ></i>
            </div>

            <div class="product-weight">
               ${bread.weight}
            </div>

           <button class="add-button button-primary js-add-to-basket"
           data-product-id ="${bread.id}">
            Add
           </button>
            
            </div>
            
        </div>
        `;

        let addToBasket = document.querySelectorAll('.js-add-to-basket');
        addToBasket.forEach((button)=>{
          button.addEventListener('click', () =>{
           console.log(button.dataset)
        });
      });
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • are you loading that script before or after the HTML you've posted – Jaromanda X Jun 26 '23 at 23:58
  • You haven't added that HTML to the DOM before calling `document.querySelectorAll()`. You need to assign it to `something.innerHTML` – Barmar Jun 27 '23 at 00:00
  • If you're adding these dynamically, you should use [event delegation](https://stackoverflow.com/questions/23508221/vanilla-javascript-event-delegation) – Barmar Jun 27 '23 at 00:01
  • To Jaromanda X, I loaded the script after i generated the HTML in javascript. To Bamar, do you mean something like this? const innerChange = document.querySelector('.js-grid-display'); innerChange.innerHTML = productHTML; – Abel Daniels Jun 28 '23 at 21:30

0 Answers0