Getting an anchor element's absolute URL with jQuery
Asked Answered
E

4

17

Given an anchor element (with something like $("a:first")), how do you get the absolute URL that the anchor points to?

Extrusive answered 30/5, 2011 at 1:54 Comment(0)
C
31

If you're using jQuery 1.6+, you can use .prop():

$("a:first").prop("href")

Prior to 1.6, you can access the href property directly on the DOM element:

$("a:first")[0].href;
Clamber answered 30/5, 2011 at 1:57 Comment(2)
Haha, I know, I was just waiting for the 5 min timeout to expire.Extrusive
Just to clarify, it's not entirely obvious, but the above does turn out to return the absolute, not the page-relative href. I didn't really believe it until I tried it. I guess that's the difference between prop() and attr() in this case.Gloriole
V
1

to get the URL attached you can do something like...

var url = $("a:first").attr('href'); this will give you the URL but doesnt guarantee absolute or relative.

To find the absolute URL you can further check

if(!url.startsWith("http")) { url = "http://www.mysite.com" + url}

Vannessavanni answered 30/5, 2011 at 1:57 Comment(2)
startsWith is definitely not a native String method. Perhaps that is an extension from some library you typically use?Louie
I agree with you. And yes it wanted to reflect the idea. We could have also used .indexOf()!=-1 instead...Vannessavanni
I
0

Without jQuery, you can leverage vanilla JavaScript:

HTMLAnchorElement: toString() returns a string containing the whole ("absolute") URL:

const anchorElement = document.createElement('a');
anchorElement.href = '/help';

console.log("anchorElement object     :", anchorElement);
console.log("anchorElement outerHTML  :", anchorElement.outerHTML);
console.log("anchorElement toString() :", anchorElement.toString());

In this example, the anchorElement uses the origin-relative URL /help for its href attribute:

<a href="/help"></a>

anchorElement.toString() returns the absolute URL:

https://stacksnippets.net/help

Note: https://stacksnippets.net/ is the domain serving the code snippet, which this page (stackoverflow.com) embeds as an iframe.

Insociable answered 21/9, 2023 at 10:39 Comment(0)
D
-2

var x = "http://lol.com/" + $("a:first").prop('href');

that should work unless it's an external url :)

Danitadaniyal answered 30/5, 2011 at 1:56 Comment(2)
why? :-s. if the <a> is relative it would add to the first url.Danitadaniyal
$("a:first") returns a jQuery object containing elements matching the selector you passed to jQuery. Adding a string to that result set won't give you anything useful.Clamber

© 2022 - 2025 — McMap. All rights reserved.