javascript - 如何引用 id 并获取链接的 href?
问题描述
问题:如何引用链接的ID?见附图 点击这里
function insertButton(refresh = false) {
var to_match = 'a[class="';
var PAGE_TYPE = 0;
if (document.location.href == "https://www.youtube.com") {
如何引用id = "video-title-link"
var anchor_tag = document.getElementById("video-title-link");
有2 个锚标签* 具有相同的类名。我想引用id="video-title-link"
if(anchor_tag.hasAttribute('href="\/watch\?v=(\S+)"')){
to_match = to_match.concat("yt-simple-endpoint style-scope ytd-rich-grid-video-renderer", '"]').getattribute('id ="video-title-link"');
PAGE_TYPE = 1;
}
}
更新: 投票
const poller = setInterval(function(){
const anchor_tags = document.querySelectorAll('a[id="video-title-link"]');
if(anchor_tags){
for (index = 0; index < anchor_tags.length ; index++){
console.log(anchor_tags[index].getAttribute('href'));
}
clearInterval(poller);
}
}, 1000);
输出: 点击这里:每个'id'的href
解决方案
您可以使用querySelector()
and.getAttribute()
来执行此操作:
const element = document.querySelector(".yt-simple-endpoint")
const href = element.getAttribute("href");
console.log(href)
<a class="yt-simple-endpoint" href="https://example.com">Link</a>
推荐阅读
- ffmpeg - 使用 ffmpeg 将 tga 转换为 mp4 时出现“解码流 #0:0 时出错:处理输入时发现无效数据”
- python - Python:抑制 parse_expr、sympy 中指数符号的扩展
- mysql - 如何使用 SQL 创建欺诈检测?
- arrays - CollectionView 错误:尝试将第 40 项插入第 0 节,但更新后第 0 节中只有 40 项
- android - Firebase Cloud Messaging 令牌在没有第三方库的情况下本机反应
- javascript - 单击时呈现贝宝结帐按钮
- javascript - 在 for 语句中使用数组为 getElementById 选择 id 返回“null”
- c# - 使用服务器端没有 TotalPage 计数的数据表分页
- nginx - 如何使用 ffmpeg 将 boxblur 添加到 rtmp 流
- react-native - 如何在 react natve 中执行此步骤