when I click the cross icon in shopping cart for first time it works well , but problem occurs when you want to add new items into shopping cart it is the time the cross icon doesn't work. as far as I know cross icon works exactly before you want to add new items the html of cart:
shopping cart html part:
<div class="cart-container col-md-4 col-lg-3">
<div class="content-container">
<div class="img-container">
<div class="img-box"><img src="images/cart-item-1.png" class="cart-img" alt=""></div>
<div class="price-box">
<h3>cart item 01</h3>
<p>$15.99/-</p>
</div>
</div>
<div class="xmark"><i class="fa-solid fa-xmark"></i></div>
</div>
</div>
(add to cart button) html part:
<div class="box">
<img src="images/menu-1.png" class="buy-coffee" alt="cappuccino">
<h3>tasty and healty</h3>
<div class="price">
$15.99
<span>$20.99</span>
</div>
<button type="button">add to cart</button>
</div>
function which remove item from shopping cart:
const crossIcons = document.querySelectorAll('.fa-xmark');
for(let crossIcon of crossIcons){
crossIcon.addEventListener("click",function(event){
this.closest('div.content-container').remove();
})
function for adding new items to shopping cart:
let addTocarts = document.querySelectorAll('.box button');
for (let addToCart of addTocarts) {
addToCart.addEventListener("click", myfunc);
function myfunc(event) {
event.preventDefault()
let boxImg
let boxSelect = addToCart.closest('div.box');
boxImg = boxSelect.children[0].getAttribute('src');
let el = ` <div class="content-container">
<div class="img-container">
<div class="img-box"><img src="${boxImg}" class="cart-img" alt=""></div>
<div class="price-box">
<h3>cart item 01</h3>
<p>$15.99/-</p>
</div>
</div>
<div class="xmark"><i class="fa-solid fa-xmark" ></i></div>
</div>`;
document.querySelector('.cart-container').innerHTML += el;
}
}
I just want to add and remove items for cart shop