Reputation: 71
We are trying a access various DOM elements from full HTML pages that are remotely fetched via XHR GET request.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/test.html", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var newdom = xhr.responseText;
var val_result = newdom.a_div.innerText;
// we want to access the text within this div, from the fetched html page?
}
}
xhr.send();
Any ideas?
Upvotes: 0
Views: 1214
Reputation: 35806
Easily enough you could do this:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'https://stackoverflow.com/questions/53661013/parsing-and-accessing-dom-elements-from-html-page-fetched-via-ajax-xhr-get-reque/53661204', true)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var dom = new DOMParser().parseFromString(xhr.responseText, 'text/html')
console.log(dom.querySelector('#question-header h1').innerText)
}
}
xhr.send()
If you copy this code as-is in your browser console, it will print the title of your StackOverflow question! Simply use the dom
variable to query for the element you are looking for in.
Upvotes: 4
Reputation: 5091
You need to create an element with
const el=document.createElement('div')
then assign its innerhtml
el.innerHTML = newdom
Then you should be able to access the nodes
Upvotes: 0