从通过Ajax XHR获取的HTML页面解析和访问Dom元素

时间:2018-12-06 23:04:45

标签: javascript dom xmlhttprequest html-parsing

我们正在尝试访问通过XHR GET请求远程获取的完整HTML页面中的各种DOM元素。

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();

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以轻松地做到这一点:

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()

如果您在浏览器控制台中原样复制此代码,它将打印您的StackOverflow问题的标题!只需使用dom变量来查询您要查找的元素。

答案 1 :(得分:0)

您需要使用

创建一个元素
const el=document.createElement('div')

然后分配其内部html

el.innerHTML = newdom

那么您应该可以访问节点