问题描述
我正在尝试向 example.com 发出提取请求,并尝试从提取的网页中将特定的 ElementID 获取到控制台日志中,但没有成功。
我已经尝试了以下代码但没有成功:
const url = "https://example.com";
fetch(url)
.then(response => response)
.then(data => {
const resData = data.text();
console.log(resData);
document.getElementById("id").innerHTML = resData;
})
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));
我会接受你的建议'。谢谢
我收到 TypeError:无法设置 null 的属性“innerHTML”
解决方法
您的问题是您当前的文档
不包含 ID 为“id”(document.getElementById("id")
) 的元素。
这导致此表达式的计算结果为 null
,这解释了您面临的错误。
在你的情况下,我会建议这样的:
创建一个新容器,您可以在其中插入 HTML 代码并使用它。
作为参考:Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
const url = "https://example.com";
fetch(url)
.then(data => {
const resData = data.text();
console.log(resData);
const responseContainer = document.createElement("div");
responseContainer.innerHTML = "";
/*
* Work with the responseContainer.
* As example to get all elements with class "example":
* responseContainer.getElementsByClassName("example")
*/
})
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));