Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to get the absolute link of an <a> tag using JavaScript/jQuery?

HTML:

<a href="3.html">No. 3</a>

JS:

$('a').attr('href') // would return the string "3.html"

How can I get the string of the full path:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('a').fullLinkAttr('href') // returns https://www.example.com/3.html

>Solution :

Getting the .href solves the problem easy:

const a = document.getElementById("a"),
  b = document.getElementById("b"),
  c = document.getElementById("c");
  
console.log("A:", a.href);
console.log("B:", b.href);
console.log("C:", c.href);
<a href="/t/hello" id="a">A</a>
<a href="hello.html" id="b">B</a>
<a href="https://stackoverflow.com/testing..." id="c">C</a>

Or a pointed out by Kaiido in the comments one could use the URL constructor:

const absolutePath = new URL("/absolute/or/relative/url", document.baseURI).href;

With jQuery:

const absolutePath = new URL($("a").attr("href"), document.baseURI).href;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading