How to show product added or removed when add or remove button is clicked?
Right now i have to pass the id of caption to get the text content. But this way i have to create same function for all products.
how to make it dynamic for every product?
document.querySelectorAll(".addProduct").forEach((btn) => {
btn.addEventListener("click", ({target}) => {
const proName = document.getElementById("flower-caption").textContent;
document.getElementById("message").textContent = `${proName} Added.`;
});
});
document.querySelectorAll(".removeProduct").forEach((btn) => {
btn.addEventListener("click", ({target}) => {
const proName = document.getElementById("flower-caption").textContent;
document.getElementById("message").textContent = `${proName} Removed.`;
});
});
<div class="product">
<figure id="caption">
<img src="images/flower.png" alt="Flowers" />
<figcaption id="flower-caption">Beautiful Flower</figcaption>
</figure>
<button type="button" class="addProduct">Add To Cart</button>
<button type="button" class="removeProduct">Remove From Cart</button>
</div>
<div class="product">
<figure id="caption">
<img src="images/parrot.png" alt="Parrot" />
<figcaption id="parrot-caption">parrot</figcaption>
</figure>
<button type="button" class="addProduct">Add To Cart</button>
<button type="button" class="removeProduct">Remove From Cart</button>
</div>
2
Answers
Use
parentNode
to get the parent of clicked btn, then selectfigcaption
‘s text.id
should be unique in html, you can use class instead.Simpler way is using closest() method.
Alos you don’t need to use any id. just use css syntax on
.querySelector()
method…And (that’s true) id must be unique on a web page