← back to all talks and articles

Internet Explorer and base elements

Internet Explorer treats the base element a bit diffently from other browser. I ran into the issue when trying to change the current page’s hash through javascript:

window.location.hash = 'some_value';

Internet explorer took the entire base URL and prepended it to the hash, resulting in an URL like http://domain.tld/http://domain.tld/#some_value. That’s clearly not my intention.

The trick lies in the href attribute for links. This actually points to the faulty long url, while its actual attribute value is only the hash:

<a id="link" href="#some_value">...</a>
// IE: http://domain.tld/#some_value
// other browser: #some_value

The trick is to replace anything before the pound when reading the href value, like so:

$('#link').attr('href').replace(/^.*(?=#)/, '');

And when trying to find links pointing at #some_value to not be too restrictive with your selector:

// finds 1 in other browsers, nothing in IE
// works like expected in all browsers; Note the *

Tricky stuff!

  • code
  • javascript
  • development
Arjan van der Gaag

Arjan van der Gaag

A thirtysomething software developer, historian and all-round geek. This is his blog about Ruby, Rails, Javascript, Git, CSS, software and the web. Back to all talks and articles?


You cannot leave comments on my site, but you can always tweet questions or comments at me: @avdgaag.