13

In the following HTML:

<a id="link" href="page.htm">Page</a>

I'm finding that document.getElementById("link").href always returns the absolute path to page.htm rather than the relative path as I have typed it. See http://jsfiddle.net/4HgAW/.

Can I guarantee that javascript will always return the absolute path, in every browser?

The reason I'm asking is that I'm grabbing the http://www.... part to check which domain the link points to, and I need it to work for internal links as well.

Flash
  • 15,945
  • 13
  • 70
  • 98

1 Answers1

23

Yes, all relevant browsers return the fully qualified URL.

If you want to retrieve the original value of the href attribute ('page.html' in this case), you can do this:

anchor.getAttribute('href')

However, that doesn't seem to work in older versions of IE (8 and below).

Live demo: http://jsfiddle.net/simevidas/4HgAW/1/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • 2
    For those of you using jQuery: jQuery also returns the original `href` attribute value when using `$('#someAnchor').attr('href')`. To get the absolute URL from a jQuery element, you have to use `$('#someAnchor').get()[0].href`. – fero Jan 16 '13 at 10:54
  • 3
    @fero jQuery offers `.prop('href')` for that purpose, so you don't have to do `[0].href`. Btw, you can do `[0]` directly, i.e. you don't need the `.get()`. – Šime Vidas Jan 16 '13 at 18:37
  • I didn't know `prop()`. Thanks. But in my case, I need the `get()` to get the underlying DOM object from a jQuery object. Just `[0]` would return the first jQuery object instead of the first DOM object returned by `get()`. – fero Jan 17 '13 at 09:59
  • @fero No, there only is one jQuery object. Individual DOM elements are not wrapped in jQuery objects, but the entire set of DOM elements is wrapped in one jQuery object. If you select multiple DOM elements, e.g. `$('.foo')`, you can get the first DOM element like so: `$('.foo')[0]`. The `.get()` is only useful when you want to get a plain (native) array of DOM elements. – Šime Vidas Jan 17 '13 at 14:17