Setting a Stylesheet via DHTML

Ever wanted to designate a style sheet via DHTML? Well, I hadn't needed to until recently. I have an application that reads an XML data island which tells the page the file name of the style sheet to use. (It could be any file of a hundred files, so I don;t want to load alternate style sheets in this case.) So here is the solution I decided on ...

First ... I created a link tag with an empty href reference. The DOM doesn't store add an item to the document's stylesheet collection unless is has an href attribute.

<FONT color=#006400><link id="mainStyle" href="" type="text/css" rel="stylesheet">

Next, I created some client side javascript that finds locates the mainStyle stylesheet reference and associates it to a specific URL where the stylesheet can be found.

<FONT color=#000080><script>
<!--//
   document.styleSheets.item("mainStyle").addImport("../css/mystyles.css");  
//-->
</script>

Of course, I don't hard code the path to the css file. Instead, I read the path from the XML data island and use that. Not much to it, but it does the job. :-)

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders

Tags:
All