首页 > 解决方案 > 如何引用 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

标签: javascriptanchorhrefconcat

解决方案


您可以使用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>


推荐阅读