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:

<html>
  <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;
    </script>
  </body>
</html>

and the resulting page show:

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

href: http://localhost/relative/link
 
Advertisement

Leave a Reply

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

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.