Applying style sheets from JavaScript

JavaScript FAQ | Styles/CSS FAQ  

Question: How do I apply another stylesheet to my document using JavaScript?

Answer: The browser loads stylesheets (CSS files) using one or more LINK commands (typically in the HEAD section of the page) like this:

<LINK rel="stylesheet" type="text/css" href="styleA.css">
<LINK rel="stylesheet" type="text/css" href="styleB.css">
<LINK rel="stylesheet" type="text/css" href="styleC.css">
JavaScript accesses stylesheets using the document.styleSheets collection. You can apply a stylesheet to the document simply by changing the property document.styleSheets[i].disabled to false for the desired stylesheet. Set disabled to true for those stylesheets that you do not currently need.

Example. The following function enables stylesheet number k and disables all other stylesheets:

function applyStyle(k) {
 if (document.styleSheets) {
  var nStyles = document.styleSheets.length;
  for (var i=0;i<nStyles;i++) {
   if (i==k) document.styleSheets[i].disabled = false;
   else      document.styleSheets[i].disabled = true;
  }
 }
}

Try it in action now:

  • Apply Style A (blue text) - this invokes applyStyle(0)
  • Apply Style B (gray text) - this invokes applyStyle(1)
  • Apply Style C (black text) - this invokes applyStyle(2)
  • Copyright © 1999-2011, JavaScripter.net.