javascript - 从 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 或类。谁能指出我正确的方向?
解决方案
.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
推荐阅读
- sql - SQL Server - 查询数据库以查找两列之间的差异
- python - 提高 Fortran 矩阵指数性能(Expokit 比 Matlab、Python 慢)
- azure - Azure Maps 请求监视
- list - 如何编写序言谓词以使用 conc(连接)操作从 List 中修剪前 N 个元素
- ios - 在 UIImageView 中更快地加载大图像
- ruby-on-rails - 如果我将 ruby 版本 2.5.1 与 rails 版本 2.3.18 一起使用会发生什么?
- javascript - 为剑道网格中的分组数据重复辅助标题
- php - 用于捕获组 ()* 的正则表达式,它使用 PHP 返回结果集及其所有出现
- json - 如何使用存储在数组中的属性名称修改 javascript 对象
- amazon-web-services - 如果 EBS 卷分离,是否可以在 AWS 上触发实例终止?