You can try accessing it like this:
function myFunction() {
var div = document.getElementsByTagName("div")[0].getAttribute("product");
var id = div.getAttribute('data-id');
}
When using the approach above, you must need to know the index value of the
div
hierarchy in the page, otherwise you will get an unexpected behavior. So I personally won't recommend it.
If you want to use JavaScript, then you may need to set an id/name attribute for your
div
elements so you can easily reference them.
<div id="divProduct" class="product" data-id="1"> </div>
You can then get the value of
data-id
attribute like this:
<script>
function myFunction() {
var plant = document.getElementById('divProduct');
var id = plant.getAttribute('data-id');
}
</script>
You can then call the
myFunction()
method by attaching an
onclick
event to your Button:
<button class="js_buy" onclick="myFunction();">Buy</button>
If you can use jQuery, then you can simply access DOM elements using selectors without the need to specify an id or name attribute or modify your HTML. For example:
<script>
$(".js_buy" ).click(function() {
var id = $(".product").attr("data-id");
});
</script>