-1
<div class="buyButtonNoPrice" data-wpid="3218954"></div>

This is the code I have tried but it does not work

var CLASS = document.querySelector("[class='buyButtonNoPrice']")
console.log(CLASS)

when I log class i am returned with this html <div class="buyButtonNoPrice" data-wpid="3218954"></div>

i have tried to get the attribute by trying this too:

console.log(CLASS)```
that sort of thing works in python but not js
Khushc
  • 1
  • 1

2 Answers2

0

querySelector is for selecting DOM elements. You've already found the element, it's in the CLASS variable.

The method for getting the value of an attribute is getAttribute(), e.g. CLASS.getAttribute("data-wpid"). But you can use the dataset property to access data-XXX attributes directly.

var CLASS = document.querySelector("[class='buyButtonNoPrice']")
var PID = CLASS.dataset.wpid;
console.log(PID)
<div class="buyButtonNoPrice" data-wpid="3218954"></div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

To select any node by an attribute, you must use brackets around the attribute name:

// example: <div data-wpid="3218954" bing="baz">...</div>
const node1 = document.querySelector('[data-wpid]')
const node2 = document.querySelector('[bing]')
assert(node1 === node2) //-> true

Once you have selected a node, you get the value of all data-* attributes from the dataset property:

// example: <div data-wpid="3218954" data-foo="bar">...</div>
const node = document.querySelector('[data-wpid]')
const wpid = node.dataset.wpid  //-> 3218954
const foo = node.dataset.foo    //-> "bar"

Using querySelector is nice because you can pass any valid CSS selector. There are other common selectors which pre-date `querySelector:

// example: <div id="foo" class="bar bing">...</div>
const byId = document.getElementById('foo')
const byClass1 = document.getElementsByClassName('bar') // returns array or null
const byClass2 = document.getElementsByClassName('bing') // returns array or null
const byTag = document.getElementsByTagName('div') // return array or null
assert(byId === byClass1[0]) //-> true
assert(byId === byClass2[0]) //-> true
assert(byId === byTag[0])    //-> true
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96