skip to Main Content
let productDetails = document.createElement("div");
productDetails.className = "product_card";

productDetails.innerHTML = `
    <img
      src="${product.image.desktop}"
      alt="${product.name}"
    />
    <div class="button-wrapper">
        <button id="btn_add_to_cart">Add to Cart</button>
    </div>
    <div class="product-details-wrapper">
        <p id="product_category">${product.category}</p>
        <h4 id="product_name">${product.name}</h4>
        <p id="product_price">$${product.price.toFixed(2)}</p>
    </div>`;

productList.appendChild(productDetails);

I created a function to add product to a cart and called it using ‘onclick’ but it’s not working
I also tried to use querySelector to get the button and add an event listener, it also didn’t work

It’s like I’m trying to use something that does not exist… Anyone to help please

2

Answers


  1. You can use event proxies,Bind a click event to the parent element.

    Login or Signup to reply.
  2. You can try this approach

    const productList = document.getElementById("content");
    
    //assuming you have a list of products
    const products = [
      {
        image: {
          desktop:
            "https://images.unsplash.com/photo-1724010930544-59b11726a226?w=800&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxmZWF0dXJlZC1waG90b3MtZmVlZHwzfHx8ZW58MHx8fHx8",
        },
        name: "Hello world",
        category: "hello galaxy",
        price: 200,
        id: 1,
      },
    ];
    
    const mappedProducts = products.map((product) => {
      return `
        <div class="product_card" id="${product.id}">
          <img src="${product.image.desktop}" alt="${product.name}" />
          <div class="button-wrapper">
            <button id="product-btn" class="product-btn">Add to Cart</button>
          </div>
          <div class="product-details-wrapper">
            <p id="product_category">${product.category}</p>
            <h4 id="product_name">${product.name}</h4>
            <p id="product_price">$${product.price.toFixed(2)}</p>
          </div>
        </div>`;
    });
    
    productList.innerHTML = mappedProducts.join(" ");
    
    document.querySelectorAll(".product-btn").forEach((item) => {
      item.addEventListener("click", () => {
        console.log(item.parentElement.parentElement.id);
      });
    });
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <div id="content"></div>
      </body>
      <script src="./script.js"></script>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search