Reputation: 159
I have a line <div class="price-box price-final_price" data-role="priceBox" data-product-id="176">
in a large html file.
I need to store the value of product-id
inside a variable, so that I can access it globally.
I'm tring to do it with
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].data-product-id;
But it's not working. What am I doing wrong?
Upvotes: 1
Views: 3242
Reputation: 18898
Snippet:
var productid = document.querySelector('div[data-role="priceBox"]').getAttribute('data-product-id');
Upvotes: 0
Reputation: 50291
If you intend to use and retrieve data_attributes in javascript, you need to use dataset
instead of only data. Also to get product-id
, you need to use camel case
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].dataset.productId;
console.log(var_productid)
<div class="price-box price-final_price" data-role="priceBox" data-product-id="176"></div>
Upvotes: 2
Reputation: 1111
dataProductId = document.querySelectorAll("div")[0].getAttribute("data-roduct-id");
Upvotes: 0
Reputation: 133
var productId = $("div[data-role='priceBox']").attr('data-product-id');
Upvotes: 0
Reputation: 1978
If you want to use pure javascript you can use the .getAttribute()
method
var var_productid = document.querySelectorAll('div[data-role="priceBox"]')[0].getAttribute('data-product-id');
if you want to use jquery, you can do this
var var_productid = $('div[data-role="priceBox"]').eq(0).attr('data-product-id');
Upvotes: 3