How to write this jquery string in pure javascript? I marked the string with a comment.
function loadGoods() {
$.getJSON('goods.json', function (data) {
var out = '';
for (var key in data){
out+='<div class="single-goods">';
out+='<h3>'+data[key]['name']+'</h3>';
out+='<img src="'+data[key].image+'">';
out+='<p>Price: '+data[key]['cost']+'</p>';
out+='<button class="add-to-cart" data-art=" '+key+' "> buy</button>';
out+='</div>';
}
document.getElementById('goods').innerHTML = out;
$('button.add-to-cart').on('click', addToCart); // this string
});
}
If write this string:
document.querySelector ('button.add-to-cart'). addEventListener ('click', addToCart);
the button catches the event by clicking only the first product card, but the other product card buttons do not catch the button click events and do not add items to the cart.
addToCart - function that I will write below for a better understanding
function addToCart:
function addToCart() {
var articul = this.getAttribute('data-art');
if (cart[articul]!=undefined) {
cart[articul]++;
}
else {
cart[articul] = 1;
}
localStorage.setItem('cart', JSON.stringify(cart) );
showMiniCart();
}
querySelectorreturns only one element. UsequerySelectorAll.