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:
$('a').fullLinkAttr('href') // returns https://www.example.com/3.html
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;