joseph michael
joseph michael

Reputation: 31

How do I find the .data() (jQuery) equivalent in JavaScript?

I have this code

 var info = $($(r).find(".BuyPriceBox")).find(".PurchaseButton").data();

r is a html page returned from an ajax GET call, which contains a button which I am trying to get the data from

which I am trying to change into the JavaScript equivalent

I can't find anything that would resemble ".data()" in JavaScript? Could anyone help me with this, and if kind enough help me translate it to JavaScript?

Upvotes: 1

Views: 485

Answers (1)

Andy
Andy

Reputation: 63524

Using a fake get call:

function getData(cb) {
  var html = [
    '<div><div class="BuyPriceBox">',
    '<button class="PurchaseButton" data-id="one">Click</button>',
    '</div></div>'
  ].join('');
  setTimeout(cb, 1000, html);
}

getData(function(html) {

  // create a new element and attach the html received
  var temp = document.createElement('div');
  temp.innerHTML = html;

  // Then use `querySelector` to grab the element
  // and get the dataset (an object)
  var button = temp.querySelector('.BuyPriceBox .PurchaseButton');
  var id = button.dataset.id; // one

});

DEMO

Upvotes: 1

Related Questions