Search code examples
javascriptgoogle-chrome-extensionxmlhttprequest

How to ask for a specific element using Xmlhttprequest parameters


The element I am looking for:

<h1 id="itemSummaryPrice" style="color: rgb(255, 255, 255);">42 - 47</h1>

I wanna make a chrome extension that uses XMLHttpRequest GET METHOD for checking a value on another Website, i know i can give the URL, parameters for scaling down the response. So my question is how do I make an URL that gives me only the element in the response that I am looking for ? if its even possible.


Solution

  • You can't request only one part (node) of a document. You'll have to request the whole thing, parse it then select from it what you want:

    var request = new XMLHttpRequest();
    request.open("GET", yourUrl);
    
    request.onload = function() {
        var doc = new DOMParser().parseFromString(request.responseText, "text/html");
        var el = doc.getElementById("itemSummaryPrice"); // the element you want
    }
    
    request.send(null);
    

    Or you can set the responseType to "document" and let the XMLHttpRequest do the parsing internally, then use responseXML:

    var request = new XMLHttpRequest();
    request.open("GET", yourUrl);
    request.responseType = "document";
    
    request.onload = function() {
        var doc = request.responseXML;
        var el = doc.getElementById("itemSummaryPrice"); // the element you want
    }
    
    request.send(null);