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?

2
  • Is a string newdom? Is a string dom? Commented Dec 6, 2018 at 23:25
  • If newdom is a dom string pleade read answers to this question stackoverflow.com/questions/494143/… Commented Dec 6, 2018 at 23:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thats great apercu, I am trying to use DOMparser with getElementById() and getElementsByClassName() instead of queryselector() ?
Same thing, use dom.getElementById or dom.getElementsByClassName :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.