How to get “raw” href contents in JavaScript

前端 未结 3 1792
孤独总比滥情好
孤独总比滥情好 2020-11-27 19:06

I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the c

3条回答
  •  我在风中等你
    2020-11-27 20:08

    Here's a code snippet you could run to test.

    const anchors = document.getElementsByTagName('a');
    
    for (let anchor of anchors) {
      let hrefFullPath = anchor.href;
      let hrefRelativePath = anchor.attributes.href.value;
    
      console.log('hrefFullPath', hrefFullPath);
      console.log('hrefRelativePath', hrefRelativePath);
    }
    

    Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.

    inner
    

    This anchor's attribute value of href is:

    document.getElementById('rel').attributes.href.value => /relative/link
    

    And anchor's href value is:

    document.getElementById('rel').href =>  http://localhost:4200/relative/link
    

    I hope it helps.

提交回复
热议问题