Modifying the style sheet of a subpage at run time
First of all, I apologize if this doesn't make sense. I am new to XHTML, CSS and JavaScript.
I understand that in XHTML the correct way to have a nested page is as follows (instead of an iframe):
<object name="nestedPage" data="http://abc.com/page.html" type="text/html"
width="500" height="400" />
If I have a nested page like this - is it possible to change the stylesheet used by the nested page at runtime using JavaScript in the parent page? Ideally, this will happen immediately, so that the nested page will never be visible with its original style sheet.
Suppose you have no control over the source code of the nested page, but it's on the same domain (don't ask)
source to share
I would suggest using an iframe for this, I don't know if an object-based way of doing this is supported.
Anyway, after loading a page from one domain, you can access all of your properties via javascript. For example, in jQuery you can use a css file.
$("link [rel=stylesheet]", myFrame).attr('href', <new-url>);
with myFrame a link to your iframe object.
source to share
Several pointers.
I've been doing some research for a while and found some tricky browser issues as well as some good solutions and suggestions on the Quirksmode and IIRC Dojo mailing lists. This resulted in the following library function for applying CSS, which I tested in major browsers:
function applyCSS(css) {
// http://www.quirksmode.org/bugreports/archives/2006/01/IE_wont_allow_documentcreateElementstyle.html
if (BrowserDetect.browser=="Safari" || BrowserDetect.browser=="Opera") { /* good for FF too */
var styleNode = document.createElement("style");
styleNode.setAttribute("type", "text/css");
styleNode.appendChild(document.createTextNode(css));
head.appendChild(styleNode);
} else {
var div = document.createElement("div");
div.innerHTML = "<p>x</p><style>"+css+"</style>";
document.body.appendChild(div.childNodes[1]);
}
}
If you do it inside an iframe, this trick might help (from TiddlyWiki code):
var doc = iframe.document;
if(iframe.contentDocument)
doc = iframe.contentDocument; // For NS6
else if(iframe.contentWindow)
doc = iframe.contentWindow.document; // For IE5.5 and IE6
// Put the content in the iframe
doc.open();
doc.writeln(content);
doc.close();
The above code generates a new iframe with some content. If you only render the iframe once, and you already know the CSS, you can simply send the tag down when rendering the iframe.
source to share