【问题标题】:Parsing And Accessing Dom Elements From HTML Page Fetched Via Ajax XHR Get Request从通过 Ajax XHR Get 请求获取的 HTML 页面解析和访问 Dom 元素
【发布时间】:2019-05-08 17:12:54
【问题描述】:

我们正在尝试从通过 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();

有什么想法吗?

【问题讨论】:

标签: javascript dom xmlhttprequest html-parsing


【解决方案1】:

你可以很容易地做到这一点:

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 变量来查询您要查找的元素。

【讨论】:

  • 太棒了,我正在尝试将 DOMparser 与 getElementById() 和 getElementsByClassName() 一起使用,而不是 queryselector() ?
  • 同样的事情,使用dom.getElementByIddom.getElementsByClassName :)
【解决方案2】:

你需要用

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

然后分配它的innerhtml

el.innerHTML = newdom

那么你应该可以访问节点了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 2016-05-02
    • 2014-05-03
    • 1970-01-01
    • 2021-10-03
    • 2016-06-05
    • 2010-11-04
    相关资源
    最近更新 更多