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.
A:
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='" + document.location.hostname + "' />");
</SCRIPT>
This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than dowing 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>
Zach Gardner
2010-08-16 16:04:00