0

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?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
SeanAA
  • 61
  • 3
  • 11
  • Is a string newdom? Is a string dom? – Mario Dec 06 '18 at 23:25
  • If newdom is a dom string pleade read answers to this question https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro – Mario Dec 06 '18 at 23:28

2 Answers2

4

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.

Preview
  • 35,317
  • 10
  • 92
  • 112
  • Thats great apercu, I am trying to use DOMparser with getElementById() and getElementsByClassName() instead of queryselector() ? – SeanAA Dec 10 '18 at 11:13
  • Same thing, use `dom.getElementById` or `dom.getElementsByClassName` :) – Preview Dec 10 '18 at 11:17
0

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

Tiago Coelho
  • 5,023
  • 10
  • 17