1

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?

1
  • 1
    .data-product-id is invalid, - is the minus operator for js engine. Since you are using data-attribute, you can access it through element.dataset.productId Commented Jul 22, 2017 at 2:37

5 Answers 5

3

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');

Sign up to request clarification or add additional context in comments.

Comments

2

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>

3 Comments

Thanks for the info.
In my question, its data-product-id. so, the camelcase will be dataProductId. Right?
Nope. It will be dataset.productId.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM
0

var productId = $("div[data-role='priceBox']").attr('data-product-id');

1 Comment

This doesn't address the need to get the first element
0
dataProductId = document.querySelectorAll("div")[0].getAttribute("data-roduct-id");

Comments

0
  • Use getAttribute
  • No need to use querySelectorAll if you only want the first item found, just use querySelector

Snippet:

var productid = document.querySelector('div[data-role="priceBox"]').getAttribute('data-product-id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.