6

How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return http://www.mysite.com/mypage.aspx from <a href="../mypage.aspx"></a>.

I have tried the following:

  1. $(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).

  2. this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.

What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.

3
  • Possible duplicate of stackoverflow.com/questions/303956/… Commented Nov 28, 2011 at 4:57
  • You might want to check out this question stackoverflow.com/questions/470832/… Commented Nov 28, 2011 at 5:02
  • 1
    @sputnick, it's definitely not a duplicate of that. This looks like your basic n00bert url propery question on the surface, but it's a little more complicated. Commented Nov 28, 2011 at 5:08

1 Answer 1

6

You can create an img element and then set the src attribute to the retrieved href value. Then when you retrieve the src attribute it will be fully qualified. Here is an example function that I have used from http://james.padolsey.com/javascript/getting-a-fully-qualified-url/:

function qualifyURL(url){
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
}
Sign up to request clarification or add additional context in comments.

2 Comments

To clarify, this works in every browser I've tested: IE 6-9, Chrome, FireFox, and Safari.
Note that, at least in Chrome, this will cause a server request for the URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.