javascript - 如何在 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
,但它不起作用(请参阅上面的错误消息)。
解决方案
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'));
推荐阅读
- .net - 云存储桶在生产中不会一次保存两个文件
- arrays - 如何使用 %c 获取字符数组中的输入字符并使用 %s 生成正确的输出?
- firebase - flutterfire 尚未配置任何应用程序。检索线程信息时出错:(ipc/send)无效的目标端口
- java - 读取 jar 中文件夹下的 xml 文件列表
- java - 我是一个初学者程序员,我不知道参数在 Java 中是如何工作的。那么它们是如何工作的呢?
- javascript - 未处理的拒绝(TypeError):stripe.redirectToCheckout 不是函数
- java - 如何打印 ISO8601 格式的日期字符串?
- http - 如何读取 http 响应正文以在 golang 中缓冲(不使用 ioutil.ReadAll())
- amazon-s3 - AWS S3 上传 401 未经授权
- git - Pro Git 中关于虚假合并的令人困惑的段落