-12
var stuff = $($(r).find(".BuyPriceBox")).find(".PurchaseButton").data();

r is the response from the AJAX call r is the web page response.

I want to write the above code in JavaScript, not using any jQuery, as node.js doesn't allow me to.

I tried document.getElementsByClassName("BuyPriceBox") but I dont know how to do .find equivalent and get the data.


Edit, Updated

Here is what i tried

var parser = new DOMParser(); 
var doc = parser.parseFromString(r, "text/html");    
console.log(JSON.stringify(query(doc, ".BuyPriceBox .PurchaseButton").dataset))

Is that correct? because i just got an error : 'TypeError: Cannot read property 'toLowerCase' of undefined'

This is what i have at the top.

var request = require("request"); 
var DOMParser = require("xmldom").DOMParser; var query = require("queryselector"); 

also im getting the request like this.

request({ url: "roblox.com/A-Lucky-Presence-item?id=380201576";, method: 'GET' }, function(err, res, r) {

Also, how do i install the modules?

guest271314
  • 1
  • 15
  • 104
  • 177
  • r is the data returned by an ajax request. – Christopher Alastair Mar 17 '16 at 16:51
  • Just FYI but `find()` returns a jQuery object, so there's no need to wrap it again: `$(r).find(".BuyPriceBox .PurchaseButton").data()` – Rory McCrossan Mar 17 '16 at 16:52
  • thanks @roryMcCrossan I was wondering Why i always had to write .find() as i was moving down elements but this has made me realise XD – Christopher Alastair Mar 17 '16 at 16:53
  • ajax calls can have multible response types. So the question is not clear. – Roland Starke Mar 17 '16 at 17:02
  • `getElementsByClassName` returns an array that you can access the first index of and then perform another `getElementsByClassName` from that position in the dom...or you can use `querySelector` as suggested in the answers to do the same. Then you need to use `dataset` to get the data. Maybe instead of calling provided solution silly you can explain what about it you don't understand or doesn't work.... – scrappedcola Mar 17 '16 at 17:04
  • @scrappedcola _"`getElementsByClassName` returns an array"_ `getElementsByClassName` does not return an `Array` ; see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName , https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection – guest271314 Mar 17 '16 at 17:10
  • So instead of freaking out maybe you could actually provide feedback on why what has been presented doesn't work? You said that you can do `document.getElementsByClassName` so I'm guessing you have jsdom so have you tried to enable queryselector? – scrappedcola Mar 17 '16 at 17:10
  • @guest271314 tomato... "Returns an array-like object of all child elements which have all of the given class names" Soo sorry array-like object that just happens to index like an array. – scrappedcola Mar 17 '16 at 17:11

2 Answers2

4
$($(r).find(".BuyPriceBox")).find(".PurchaseButton").data();

Should roughly translate to

r.querySelector(".BuyPriceBox .PurchaseButton").dataset

where r is of type object (node).

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    `r` is not a node. It must be a htmlString since OP is saying that it is coming as a response. – Rajaprabhu Aravindasamy Mar 17 '16 at 16:53
  • `r` is `document` , correct ? – guest271314 Mar 17 '16 at 16:54
  • `r is the data returned by an ajax request` – Rory McCrossan Mar 17 '16 at 16:54
  • 4
    @ChristopherAlastair If it is a silly stuff, then why did you post a silly question? – Rajaprabhu Aravindasamy Mar 17 '16 at 16:55
  • 1
    @ChristopherAlastair Can you include value of `r` at Question ? – guest271314 Mar 17 '16 at 16:55
  • 1
    If `$(r).find(".BuyPriceBox")` is working then I believe this is some node and @ChristopherAlastair, your question was how to transform that silly code to vanila JavaScript. – The Alpha Mar 17 '16 at 16:55
  • @ChristopherAlastair _"I already did include the value"_ No, actual text of or object `r` does not appear at original Question. Is `r` a `document` ? _"My question isnt silly"_ You initially used , brought the term "silly" into Question at comment. Can you include actual text of `r` at Question ? – guest271314 Mar 17 '16 at 17:03
  • 1
    If $(r) produces something that has a .find() method, r is probably a html element name or a selector. Or does $() wrapped around a responseText give access to .find() in non-elements? It matters because if $(r) produces a node, the answer is .querySelector. If $(r) is a string or something, you'll need to use .search() or a regular expression. – Shilly Mar 17 '16 at 17:05
  • 1
    @ChristopherAlastair _"R ISNT TEXT. ITS THE RESPONSE. DOES IT MATTER ANYWAY."_ ? Yes, it matters. If it did not matter the Question would not be necessary as expected result would have been achieved by you using `js` attempts at Question ? – guest271314 Mar 17 '16 at 17:05
  • I just got this error. var info = r.querySelector(".BuyPriceBox .PurchaseButton").dataset; ^ TypeError: r.querySelector is not a function – Christopher Alastair Mar 17 '16 at 17:10
  • @ChristopherAlastair Is `r` a `document` or text ? – guest271314 Mar 17 '16 at 17:11
  • That's because this answer is wrong. `r` does not have an function called `querySelector` unless it is an `HTMLDocument`. – Tim Mar 17 '16 at 17:12
  • @Tim Well, that is what viewers of this Question have been attempting to determine: What is `r` ? Note also that `.querySelector()` can be called on `Element` as well https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector – guest271314 Mar 17 '16 at 17:13
  • @guest271314 `r is the data returned by an ajax request.`, That would be a string, or an object (JSON). But JSON does not work with class names, so I conclude it is an HTML string. – Tim Mar 17 '16 at 17:14
  • @Tim _"r is the data returned by an ajax request., That would be a string, or JSON"_ How could you possibly determine this accurately given description of `r` at Question ? – guest271314 Mar 17 '16 at 17:15
  • @guest271314 `XMLHttpRequest.responseText Read only Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.` https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText – Tim Mar 17 '16 at 17:17
  • R is not json, as already stated. R Is a page. I will give you the page. http://www.roblox.com/A-Lucky-Presence-item?id=380201576 – Christopher Alastair Mar 17 '16 at 17:18
  • @Tim A response from `$.ajax()` could be a `document` object , from `XMLHttpRequest` could also be a `Blob` or text. It is unclear what `r` is at Question – guest271314 Mar 17 '16 at 17:19
  • @ChristopherAlastair The link does not indicate what actual response from ajax is ? – guest271314 Mar 17 '16 at 17:21
  • @guest271314 If it is a response from `$.ajax()`. Yes. If. – Tim Mar 17 '16 at 17:21
  • @guest271314. The ajax request just gets the whole page. That's it. I just want the data from that big green buy butto. – Christopher Alastair Mar 17 '16 at 17:22
  • Can you include the `$.ajax()` portion of `js` at Question ? That is , how you request page, options set ? – guest271314 Mar 17 '16 at 17:23
  • $.get(link).success(function(r){ – Christopher Alastair Mar 17 '16 at 17:24
  • @ChristopherAlastair Here, `$.get("http://www.roblox.com/A-Lucky-Presence-item?id=380201576")` logs `XMLHttpRequest cannot load http://www.roblox.com/A-Lucky-Presence-item?id=380201576&_=1458235306233. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.` at `console` . The page does not appear to allow cross-origin requests ? Do you receive the same error message ? If not, why ? – guest271314 Mar 17 '16 at 17:25
  • No I do not @guest. I just run it from the site. There is no error. I've been using ajax with this site for years – Christopher Alastair Mar 17 '16 at 17:27
  • I just want to know how would I get the javascript equivalent e.e – Christopher Alastair Mar 17 '16 at 17:29
  • @ChristopherAlastair If response is actually a string, Try `var parser = new DOMParser(); var doc = parser.parseFromString(r, "text/html"); doc.querySelector(".BuyPriceBox .PurchaseButton").dataset` – guest271314 Mar 17 '16 at 17:31
  • The error is "DOMParser" is not defined. I am running this in node.js btw – Christopher Alastair Mar 17 '16 at 17:33
  • @ChristopherAlastair _"The error is "DOMParser" is not defined. I am running this in node.js btw"_ Have you included `xmldom` ? See https://www.npmjs.com/package/xmldom – guest271314 Mar 17 '16 at 17:35
  • Thanks. But could you show an example of how it works? – Christopher Alastair Mar 17 '16 at 17:39
  • @ChristopherAlastair The linked documentation at https://www.npmjs.com/package/xmldom shows an example ? Try `var DOMParser = require("xmldom").DOMParser; var doc = new DOMParser().parseFromString(r, "text/html"); var data = doc.querySelector(".BuyPriceBox .PurchaseButton").dataset` – guest271314 Mar 17 '16 at 17:41
  • There was an error again. It said doc.querySelector is not a function – Christopher Alastair Mar 17 '16 at 17:46
  • @ChristopherAlastair _"There was an error again. It said doc.querySelector is not a function"_ Can you reproduce error at http://www.node-console.com/script/code ? See http://www.node-console.com/service/node/help – guest271314 Mar 17 '16 at 17:49
  • I did the exact thing you asked me to do. I ran in node. And I put the require at the top – Christopher Alastair Mar 17 '16 at 17:50
  • @ChristopherAlastair Not certain what issue is ? Does solution provided by Tim at http://stackoverflow.com/a/36067211/ return expected results ?, resolve Question ? – guest271314 Mar 17 '16 at 17:51
  • i didnt try tim's... too large a code. – Christopher Alastair Mar 17 '16 at 17:53
  • do i need to install an npm to use querySelector? – Christopher Alastair Mar 17 '16 at 17:53
  • @ChristopherAlastair _"do i need to install an npm to use querySelector?"_ Apparently, see https://www.npmjs.com/package/queryselector – guest271314 Mar 17 '16 at 17:55
  • It still says undefined. It must be to do with the way im using it. Are you sure it needs parsing? – Christopher Alastair Mar 17 '16 at 18:02
  • @ChristopherAlastair _"Are you sure it needs parsing?"_ No, not sure. This is why asked what `r` is ? The response could be a `document` , or other object ? Earlier, you indicated _"R ISNT TEXT."_ ? Try `typeof r` at response of ajax ; what is logged ? – guest271314 Mar 17 '16 at 18:07
  • @ChristopherAlastair Tried `$.get("http://www.roblox.com/A-Lucky-Presence-item?id=380201576", function(r) { var parser = new DOMParser(); var doc = parser.parseFromString(r, "text/html"); console.log(JSON.stringify(doc.querySelector(".BuyPriceBox .PurchaseButton").dataset)) })` at `console`, logged `{"expectedCurrency":"1","assetType":"Hat","se":"item-privatesale-buyforbestprice","itemName":"A Lucky Presence","itemId":"380201576","expectedPrice":"8600","productId":"32660713","expectedSellerId":"29736242","userassetId":"3514787372","bcRequirement":"0","sellerName":"D0wn_L0ad"}` here – guest271314 Mar 17 '16 at 18:12
  • Still says not defined. I used the exact same code. But try it in nodejs btw. – Christopher Alastair Mar 17 '16 at 18:15
  • This is what i have at the top.var request = require("request"); var DOMParser = require("xmldom").DOMParser; var query = require("queryselector"); – Christopher Alastair Mar 17 '16 at 18:16
  • also im getting the request like this. 'request({ url: "http://www.roblox.com/A-Lucky-Presence-item?id=380201576", method: 'GET' }, function(err, res, r) {' – Christopher Alastair Mar 17 '16 at 18:18
  • Did you use `query(el, selector)` pattern https://www.npmjs.com/package/queryselector#queryel-selector instead of `.querySelector()` – guest271314 Mar 17 '16 at 18:19
  • @ChristopherAlastair Not entirely certain about order of returned arguments at `nodejs`, though at jQuery `r` would be first parameter; e.g.; `function(r, res, err)` , where `r` represents `responseText` , `res` would represent `textStatus` , `err` `jqXHR` object – guest271314 Mar 17 '16 at 18:20
  • I tried this. var parser = new DOMParser(); var doc = parser.parseFromString(r, "text/html"); console.log(JSON.stringify(query(".BuyPriceBox .PurchaseButton", doc).dataset)) It says an error on behalf of the index.js module script now. WTF – Christopher Alastair Mar 17 '16 at 18:22
  • @ChristopherAlastair Did you read the linked documentation at https://www.npmjs.com/package/queryselector#queryel-selector _"Returns the first match of selector on `el` and its `children`."_ ? `doc` would be first parameter passed to `query()` , e.g,; `query(doc, ".BuyPriceBox .PurchaseButton")` – guest271314 Mar 17 '16 at 18:24
  • Your order of parameters at `request` appears to be correct https://www.npmjs.com/package/request . Note, have not used `nodejs` frequently here , though documentation appears detailed – guest271314 Mar 17 '16 at 18:28
  • Here is what i tried 'var parser = new DOMParser(); var doc = parser.parseFromString(r, "text/html"); console.log(JSON.stringify(query(doc, ".BuyPriceBox .PurchaseButton").dataset))'. Is that correct? because i just got an error : 'TypeError: Cannot read property 'toLowerCase' of undefined' – Christopher Alastair Mar 17 '16 at 18:30
  • Is there a space between `".BuyPriceBox"` an `".PurchaseButton"` at selector ? Not certain if a `JSON` package needs to be installed ? Tried `console.log(query(doc, ".BuyPriceBox .PurchaseButton").dataset)` ? – guest271314 Mar 17 '16 at 18:31
  • Still says the same error. the error lies in the index.js for the queryselector module file – Christopher Alastair Mar 17 '16 at 18:33
  • Could it be `.dataset` ? – guest271314 Mar 17 '16 at 18:34
  • This is what im doing ' var parser = new DOMParser(); var doc = parser.parseFromString(r, "text/html"); console.log(query(doc, ".BuyPriceBox .PurchaseButton").dataset)' Same error... – Christopher Alastair Mar 17 '16 at 18:35
  • Same error without dataset. Ugh this is really bugging me – Christopher Alastair Mar 17 '16 at 18:39
  • It could possibly help to reproduce the actual `js` that you are using at for example http://www.node-console.com/script/code . Perhaps also add `nodejs` tag to your Question ? , for viewers that use nodejs to provide solutions ? – guest271314 Mar 17 '16 at 18:43
  • Also, update original Question with most recent attempts at `js` posted at comments to resolve issues ? – guest271314 Mar 17 '16 at 18:49
  • how do i install the modules? – Christopher Alastair Mar 17 '16 at 18:51
  • @ChristopherAlastair Just noticed there is a syntax error at `;` at `{ url: "roblox.com/A-Lucky-Presence-item?id=380201576";, method: 'GET' }` – guest271314 Mar 17 '16 at 18:55
  • @ChristopherAlastair See https://docs.npmjs.com/getting-started/installing-npm-packages-globally , http://stackoverflow.com/questions/5817874/how-do-i-install-a-module-globally-using-npm – guest271314 Mar 17 '16 at 18:57
0

Assuming that the variable r is an HTML string or an HTML element and you would have to following functions:

function parseHTML(htmlString) {

    if (htmlString instanceof HTMLElement) {
        return htmlString;
    }

    var el = document.createElement('html');
    el.innerHTML = htmlString;
    return el;
}
function toArray(htmlCollection) {
    return [].slice.call(htmlCollection);
}

function findIn(className, parent) {

    var elements = toArray(document.getElementsByClassName(className));

    return elements.filter(function (element) {
        isDescendantOf(element, parent);
    });
}

function isDescendantOf(element, parent) {
    while (element = element.parentElement) { 
        if (element === parent) {
            return true;
        }
    }

    return false;
}

You could rewrite you code to:

var data = [];

findIn('.BuyPriceBox', r).forEach(function (element) {

    data.concat(findIn('.PurchaseButton', element).map(function (element) {
        return element.dataset;
    }));
});
Tim
  • 5,521
  • 8
  • 36
  • 69