querySelectorAll() to html from another page

3.7k Views Asked by At

Good morning, I am geting html of another page by AJAX:

var xml = new XMLHttpRequest()
xml.onreadystatechange = function () {
    if (xml.readyState == 4) {
        // here I need to work with data
        // xml.responseText
    }
}
xml.open("GET", url, false);
xml.send(null)

How I can apply querySelectorAll() to html content of another page?

2

There are 2 best solutions below

0
On BEST ANSWER

You could create new document and put responseText into it. Then you can use querySelectorAll(). Here is your onreadystatechange function:

function () {
    if (xml.readyState == 4) {
        var container = document.implementation.createHTMLDocument().documentElement;
        container.innerHTML = xml.responseText;
        var nodeList = container.querySelectorAll('selector');
    }
}
2
On

If your response is valid XML, you can try xml.responseXml.

If that's not the case, you might consider using a DocumentFragment:

var doc = document.createDocumentFragment();
var div = document.createElement("div");
div.innerHTML = xml.responseText;
doc.appendChild(div);

var nodes = doc.querySelectorAll("...");