Archive for November, 2008

Changing Stylesheets with Javascript

Thursday, November 27th, 2008

Here’s a quick and easy way to change stylesheets on the fly using a little javascript and jQuery:

function changeCSS(newStylesheetLocation) {
  var css = document.createElement("link");
  css.href = newStylesheetLocation;
  css.rel = "stylesheet";
  css.type = "text/css";
  $("link").remove();
  $("head").get(0).appendChild(css);
}

and


This assumes that:

  • You’ve only got one stylesheet in the head section of your document
  • You’ve used a link tag to include your stylesheet

If you’ve used inline stylesheets, @import or have multiple link tags, you’ll need to adjust the javascript function to suit your needs.