I need help, addToCartBtns return a nodelist length 0, I don’t know why, it’s work with getElementbyClassName…………………………………………………………………………….
const dessertCartContainer = document.getElementById("desserts-card-container");
fetch("./data.json")
.then((response) => response.json())
.then((data) => showProducts(data));
const showProducts = (productsArr) => {
productsArr.forEach(({ image, category, name, price }, index) => {
dessertCartContainer.innerHTML += `
<div>
<img src="${image.mobile}" class="product-img" />
<div class="home-qty-states">
<button id="${index}" class="btn add-to-cart-btn home-state">
<img src="./assets/images/icon-add-to-cart.svg" />
Add to Cart
</button>
<div class="btn qty-state">
<button class="btn-qty">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="2" fill="none" viewBox="0 0 10 2"><path fill="var(--icon-clr, #fff)" d="M0 .375h10v1.25H0V.375Z"/></svg>
</button>
<span id="currentProductCount">1</span>
<button class="btn-qty">
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" fill="none" viewBox="0 0 10 10"><path fill="var(--icon-clr, #fff)" d="M10 4.375H5.625V0h-1.25v4.375H0v1.25h4.375V10h1.25V5.625H10v-1.25Z"/></svg>
</button>
</div>
</div>
<p class="product-category">${category}</p>
<h3 class="product-name">${name}</h3>
<p class="product-price">$${price.toFixed(2)}</p>
</div>
`;
});
};
const addToCartBtns = document.querySelectorAll(".add-to-cart-btn");
console.log(addToCartBtns);
3
you need to select the buttons after they’ve been created ,you need to move the selection inside the showProducts function
const showProducts = (productsArr) => {
productsArr.forEach(({ image, category, name, price }, index) => {
// ... existing code ...
});
const addToCartBtns = document.querySelectorAll(".add-to-cart-btn");
console.log(addToCartBtns);
};