Within my template, there are numerous links like this:
<a href="javascript:void(0);" class="add_to_cart" data-slug="{{ product.slug }}">Add</a>
I am trying to click on a link and retrieve the specific data-slug
associated with it. I attempted to achieve this using JavaScript by selecting all the links.
var add_to_cart = document.getElementsByClassName('add_to_cart');
Next, I used a for
loop:
for(var i = 0; i < add_to_cart.length; i++) {
product_slug = add_to_cart[i].getAttribute('data-slug')
add_to_cart[i].onclick = function() {
console.log(product_slug)
}
}
However, when clicking on a link, the console.log
always displays the data-slug
of the last link in the template. How can I correct this behavior to retrieve the data-slug
of the clicked item? Your assistance is greatly appreciated.