I have a products.html site where all the product are listed in a container and where you can add them to cart by using "Add to cart" button. My sites body looks like this
<body>
<header>
<nav class="navbar">
<ul class="nav-links">
<li><a href="index.html">Front Page</a></li>
<li><a href="register.html">Register</a></li>
<li><a href="users.html">List Users</a></li>
<li><a href="products.html">List Products</a></li>
<li><a href="cart.html">Shopping Cart</a></li>
</ul>
</nav>
</header>
<main>
<h1>Products</h1>
<div id="notifications-container"></div>
<div id="products-container"></div>
</main>
<footer>
<p>Copyright © 2020 diipadaa etc etc.</p>
</footer>
<template id="product-template">
<div class="item-row">
<h3 class="product-name"></h3>
<p class="product-description"></p>
<p class="product-price"></p>
<button>Add to cart</button>
</div>
</template>
<script src="js/utils.js"></script>
<script src="js/products.js"></script>
I have multiple product which i read and place them into the site by using the clone method.
const baseContainer = document.querySelector('#products-container');
const productTemplate = document.querySelector('#product-template');
products.forEach(product => {
const { name, description, price, _id } = product;
const productContainer = productTemplate.content.cloneNode(true);
productContainer.querySelector('.product-name').id = `name-${_id}`;
productContainer.querySelector('.product-name').textContent = name;
productContainer.querySelector('.product-description').id = `description-${_id}`
productContainer.querySelector('.product-description').textContent = description;
productContainer.querySelector('.product-price').id = `price-${_id}`;
productContainer.querySelector('.product-price').textContent = price;
document.getElementsByTagName('button').forEach(elem => {
console.log(elem);
});
baseContainer.append(productContainer);
});
If i have for example 15 products on the site how can i listen to every "Add to cart" button click and call a function to it. the buttons have no id or class. forEach doesnt work for me so it doesnt regonize that there is multiple buttons?
CodePudding user response:
After you clone the button, you should give it an attribute to define what product it is associated with. Something like
products.forEach(product => {
const { name, description, price, _id } = product;
const productContainer = productTemplate.content.cloneNode(true);
//add a reference to the product ID in the button
productContainer.setAttribute("data-productID", _id);
...
CodePudding user response:
Change
document.getElementsByTagName('button')
to
productContainer.getElementsByTagName('button')
Before you append, it does not exist in the document.