kashish
kashish

Reputation: 159

Using queryselectorall with classes

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

Answers (5)

KevBot
KevBot

Reputation: 18898

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

Upvotes: 0

brk
brk

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

Haikel Fazzani
Haikel Fazzani

Reputation: 1111

dataProductId = document.querySelectorAll("div")[0].getAttribute("data-roduct-id");

Upvotes: 0

knizer
knizer

Reputation: 133

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

Upvotes: 0

CumminUp07
CumminUp07

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

Related Questions