首页 > 解决方案 > 从 DOM 标头资源中提取 HTML 链接(没有 ID 或类)

问题描述

我在网站上有以下代码结构:

<link rel="amphtml" href="http://example.com/?amp"></head>

我希望仅在出现“amphtml”rel 值的页面上提取 html 链接。我尝试了以下代码,但它破坏了未出现该标签的 url 上的应用程序。

var ampLink_txt = document.querySelector("link[rel=amphtml]").getAttribute("href");

我无权更改 HTML 文档,我不能添加任何 ID 或类。谁能指出我正确的方向?

标签: javascriptdomselectors-api

解决方案


.querySelectornull如果没有找到可能会返回。您应该首先检查它是否为空:

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


推荐阅读