Forum Moderators: open
I have a problem regarding <link> href attribute. I have a function that dynamicly writes to <head> tag the <link> tag with attribute href which points to the certain .css file. href property is set to site root eg. href="/css/print.css" - which is simply done by document.write('<link href="....">'). The thing is browser doesn't interpret newly created <link> tag so that the <link> would have a document relative path instead just writes literal and the path is not valid. So the question is how do i "write" to the <head> tag that href attribute would be interpreted. Hope I was clear. I appreciate and help or tips. Thanks.
function Preview() {
var query;
var title;
var hidden;
title = window.location.href;
query = title.indexOf('?');
if (query!= -1) {
if (title.substr(query+1) == 'print=yes') {
hidden = document.getElementsByTagName("link");
hidden[0].disabled = true;
document.write('<link href="/css/print.css" rel="stylesheet" type="text/css" media="screen">');
document.write('<link href="/css/print.css" rel="stylesheet" type="text/css" media="print">');
}
}
}
function Preview() {
var query;
var title;
var hidden;
var domain;
domain = document.location.hostname;
title = window.location.href;
query = title.indexOf('?');
if (query!= -1) {
if (title.substr(query+1) == 'print=yes') {
hidden = document.getElementsByTagName("link");
hidden[0].disabled = true;
document.write('<link href="'+domain+'"/css/print.css" rel="stylesheet" type="text/css" media="screen">');
document.write('<link href="'+domain+'"/css/print.css" rel="stylesheet" type="text/css" media="print">');
}
}
}
... and it still doesn't work. Any ideas?
[pre]
function addSheet(href)
{
var sheet = document.createElement("link");
sheet.rel = "stylesheet";
sheet.type = "text/css";
sheet.href = href;
sheet.media = "screen";
document.getElementsByTagName("head")[0].appendChild(sheet);
}
addSheet('test.css')[/pre] A few notes:
- I think only IE supports this usage of createElement:
createElement('a whole opening tag with attributes')
createStyleSheet is also IE only
I amended the function and I think it might be more elegant solution then createElement method:
Function Preview() {
var title;
var query;
title = document.location.href;
query = title.indexOf('?');
if (query!= -1) {
if (title.substr(query+1) == 'print=yes') {
document.getElementById("default_css").href = "/css/print.css";
}
}
}
Preview();
I have a default .css in the link tag with id=default_css which href attribute is simply replaced when a function is called. Any thoughts?
Your query string parsing approach forgets the convenience of a location.search property, and isn't capable of handling queries that have further params, or hash params, but it works for now, so who cares.