How can i use a button within a div created in javascript

  Kiến thức lập trình
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

New contributor

user2947096 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

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

New contributor

desong kong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT