How do I set a page's base href in Javascript?

Zach Gardner picture Zach Gardner · Aug 16, 2010 · Viewed 42.5k times · Source

I want to set a page's base href attribute in Javascript based off of the current hostname. I have generated HTML pages that can be viewed on different hostnames, which means generating a base href tag will work in one hostname but will be incorrect in the other.

Answer

Zach Gardner picture Zach Gardner · Aug 16, 2010

The correct way of doing this is to do a document.write of the tag based off the current hostname:

Correct:

<script type="text/javascript">
document.write("<base href='http://" + document.location.host + "' />");
</script>

This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than doing the following:

Incorrect:

<script type="text/javascript">
var newBase = document.createElement("base");
newBase.setAttribute("href", document.location.hostname);
document.getElementsByTagName("head")[0].appendChild(newBase);
</script>