如何从XMLHttpRequest响应中按类名过滤元素? [重复]

I'm working on a dynamic navigation bar that uses the XMLHttpRequest function in vanilla JS to get content a certain div class from a link within the site. I'm currently trying to figure out how to only filter out a div with class pageInner from response variable resp, like how find() is used to filter elements by class name from an AJAX response variable in jQuery.

JS:

var request = new XMLHttpRequest();
request.open('GET', this.href, true);

request.onload = function() {
      if (this.status >= 200 && this.status < 400) {
      var resp = this.response;

      document.querySelector('.pageInner').innerHTML = resp.querySelectorAll('.pageInner')[0]; \\ incorrect code
}
};

request.send();
评论
  • aut_id
    aut_id 回复

    querySelectorAll works on DOM elements. Not on string received in API.

    So you need to append your response in DOM and then try for querySelectorAll.

    喜欢。

    document.querySelector('body').appendChild(resp);
    

    然后

    document.querySelector('.pageInner').innerHTML = (resp.querySelectorAll('.pageInner')[0]).innerHTML;
    

    确保然后删除临时添加的元素。

    Also Instead of body You can use a div with display:none property. So that your display output won't have any affect. And after all your operations you can remove that div from DOM.