Search code examples
jquerycssinheritanceiframestylesheet

How to dynamically change the stylesheet of an HTML page within an iFrame of another page?


I have a web page that makes use of the jQuery UI themes. Within this page, there's an iFrame holding another HTML document that also makes use of the jQuery UI themes. Now, I have made my own theme selecter, and I'd like to know the easiest way to have it affect the page within the iFrame. For example, whenever the user selects a new theme, I simple do something like:

<link id="uiTheme" rel="stylesheet" type="text/css" href="ui/smoothness.css" />
$("#uiTheme").attr("href", "ui/" + newTheme + ".css");

Where newTheme is the string literal of a different them (all done through a select box, and I know it all works and such). Now, how can I change the sheet being used within the frame to match that of the main page? I guess my question is how can I use the jQuery selector to grab the link with an id of innerTheme to change it's href attribute to the same stylesheet? Furthermore, do I even need to worry about this, or will the ui-theme of the outer page automatically descend into the frame without the frame's page itself linking to a stylesheet?

If my question is a bit confusing, I apologize. I can try to clear anything up if need be.


Solution

  • You don't have to get a reference to their link element - just add your own and it will override.

    var link = document.createElement('link');
    link.href = "http://full.domain.com/ui/smoothness.css";
    link.type = 'text/css';
    link.rel = 'stylesheet';
    $('head', frameName )[0].appendChild(link);
    

    However, you won't be able to modify anything in the other frame if it's coming from another domain. So if it's being served from the same domain - it may be easier to just make the change on the original page. If it's coming from another site - sadly you're out of luck.