首页 > 解决方案 > 如何在 XMLHttpRequested 字符串上使用 getElementByClassName?

问题描述

function getNotRec(articleLink) {
  var req = new XMLHttpRequest();
  req.open("GET", articleLink, true);
  req.onreadystatechange = function(aEvt) {
    if (req.readyState === 4) {
      if (req.status === 200) {
        //console.log(req.responseText);
        findNotRecTag(req.responseText);
      }
      else {
        console.log("Error loading page\n");
      }
    }
  };
  req.send(null);
}

function findNotRecTag(htmlText) {
  var notRec = htmlText.getElementsByClassName("t_black");    //here
  for (var i = 0; i < notRec.length; i++) {
    console.log("notrec" + notRec[i].innerText);
  }
}

我希望使用 JavaScript 在另一个网站上获得一些“课程”。所以我正在使用 XMLHttpRequest 并成功接收。

但是当我尝试从收到的类中提取一些类时,我在控制台上遇到错误:

"Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined",    
"Uncaught TypeError: Cannot read property 'querySelector' of undefined"

我认为 Chrome 知道我在做什么,但她是.. 不是那样的,我猜

主要问题:有什么方法可以getElementsByClassName在字符串上使用或类似的东西吗?

我也尝试过querySelector,但它不起作用(请参阅上面的错误消息)。

标签: javascript

解决方案


req.responseText显然是undefined根据您收到的错误消息。为了回答您的核心问题,以下是您从 a 中选择元素的方法string

// here's your string
const htmlText = `<div><p class="p">fsdf</p><p class="p">wfdfds<p></div>`

// create an element
const fakeEl = document.createElement('div')
// and put the htmlText as innerHTML on that element
fakeEl.innerHTML = htmlText;

// now you can use all kinds of selector methods on that element
console.log(fakeEl.getElementsByClassName('p'));
console.log(fakeEl.querySelectorAll('.p'));


推荐阅读