How to get "raw" href contents in JavaScript

JavascriptAnchorHrefRelative Url

Javascript Problem Overview


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 contents of href against /^https?:///.

But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:

<a id="rel" href="/relative/link">inner</a>

accessing

document.getElementById("rel").href

returns

http://example.com/relative/link

How can I access the raw data in the href attribute?

Alternately, is there a better way to find relative links?

Javascript Solutions


Solution 1 - Javascript

Try the getAttribute method instead.

Solution 2 - Javascript

Typical. I figured it out myself almost immediately after posting the question.

instead of:

anchor.href

use:

anchor.getAttribute("href")

Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)

Solution 3 - Javascript

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.

<a id="rel" href="/relative/link">inner</a>

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwfaulkView Question on Stackoverflow
Solution 1 - JavascriptGumboView Answer on Stackoverflow
Solution 2 - JavascriptwfaulkView Answer on Stackoverflow
Solution 3 - JavascriptAlan DongView Answer on Stackoverflow