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.

Taz
  • 3,718
  • 2
  • 37
  • 59
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
  • Possible duplicate of http://stackoverflow.com/questions/303956/jquery-select-a-which-href-contains-some-string – Gilles Quénot Nov 28 '11 at 04:57
  • You might want to check out this question http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue – Brian Fisher Nov 28 '11 at 05: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. – Devin Burke Nov 28 '11 at 05:08

1 Answers1

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;
}
Brian Fisher
  • 23,519
  • 15
  • 78
  • 82