Programmatically Retrieve StyleSheet Url’s Referenced in your Page using JavaScript

I came across a requirement where the stylesheets referenced by a page had to be listed. The user was then given the ability to disable the stylesheet he did not want. Here’s how we can use the document.styleSheets collection to retrieve the collection of styleSheet objects that are referenced using a <link> and then disable the stylesheet the user does not desire. A portion of the code is as given here:

<html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title>    <link href="CSS/FloatDes.css" rel="stylesheet"    title="Float layout" type="text/css" />    <link href="CSS/RoundCorners.css" rel="stylesheet"    title="Rounded Corners" type="text/css" /> 

    <script type="text/javascript">        for (i = 0; i < document.styleSheets.length; i++) {            alert(document.styleSheets[i].title);            alert(document.styleSheets[i].href);        }    </script></head><body>

</body></html>

Similarly, if you have imported stylesheets using @import, you can access the style sheets using document.styleSheets[i].imports.

To disable a stylesheet programmatically, use this piece of code:

document.styleSheets[i].disabled = true;

To check if the styleSheet collection is supported on your browser, use this :

 if (typeof document.styleSheets != "undefined")

This code has been tested on IE7 and Firefox 3

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis
This entry was posted in CSS, JavaScript, Syndicated. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree