How to get “raw” href contents in JavaScript

本小妞迷上赌 提交于 2019-11-26 22:36:57

Try the getAttribute method instead.

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.)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!