我在网站上有以下代码结构:
<link rel="amphtml" href="http://example.com/?amp"></head>
我期待仅在出现“amphtml”rel值的页面上提取html链接。我尝试了以下代码,但它打破了不显示该标记的网址上的应用程序。
var ampLink_txt = document.querySelector("link[rel=amphtml]").getAttribute("href");
我无权更改HTML文档,我无法添加任何ID或类。任何人都能指出我正确的方向吗?
如果没有找到,.querySelector
可能会返回null
。你应该先检查它是否为空:
const ampLink = document.querySelector("link[rel=amphtml]")
if (ampLink) {
const ampLink_txt = ampLink.getAttribute("href")
// ...
}
见https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector