Javascript Relative and Absolute URLs

I recently discovered a small oddity in javascript link elements.  Simply stated, if you access the ‘href’ attribute using getAttribute(‘href’) the result will be different than accessing it with simply ‘href’.  

The getAttribute will return the relative link, where the direct call will return the absolute. 

Here’s the test:

  <body >
    <a href="/relative/link" id='rellink'>
      Relative Link</a>
    <div id='answer1'></div>
    <div id='answer2'></div>
    <script type='text/javascript'>
      var link, a1,a2;
      link = document.getElementById('rellink');
      a1 = document.getElementById('answer1');
      a2 = document.getElementById('answer2');
      a1.innerHTML =  "getAttribute('href'): "
      + link.getAttribute('href');
      a2.innerHTML = "href: " + link.href;

and the resulting page show:

Relative Link
getAttribute('href'): /relative/link

href: http://localhost/relative/link

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s