Replacing css file on the fly (and apply the new style to the page)

You can include all the stylesheets in the document and then activate/deactivate them as needed.

In my reading of the spec, you should be able to activate an alternate stylesheet by changing its disabled property from true to false, but only Firefox seems to do this correctly.

So I think you have a few options:

Toggle rel=alternate

<link rel="stylesheet"           href="https://stackoverflow.com/questions/19844545/main.css">
<link rel="stylesheet alternate" href="light.css" id="light" title="Light">
<link rel="stylesheet alternate" href="https://stackoverflow.com/questions/19844545/dark.css"  id="dark"  title="Dark">

<script>
function enableStylesheet (node) {
  node.rel="stylesheet";
}

function disableStylesheet (node) {
  node.rel="alternate stylesheet";
}
</script>

Set and toggle disabled

<link rel="stylesheet" href="https://stackoverflow.com/questions/19844545/main.css">
<link rel="stylesheet" href="light.css" id="light" class="alternate">
<link rel="stylesheet" href="https://stackoverflow.com/questions/19844545/dark.css"  id="dark"  class="alternate">

<script>
function enableStylesheet (node) {
  node.disabled = false;
}

function disableStylesheet (node) {
  node.disabled = true;
}

document
  .querySelectorAll('link[rel=stylesheet].alternate')
  .forEach(disableStylesheet);
</script>

Toggle media=none

<link rel="stylesheet" href="https://stackoverflow.com/questions/19844545/main.css">
<link rel="stylesheet" href="light.css" media="none" id="light">
<link rel="stylesheet" href="https://stackoverflow.com/questions/19844545/dark.css"  media="none" id="dark">

<script>
function enableStylesheet (node) {
  node.media="";
}

function disableStylesheet (node) {
  node.media="none";
}
</script>

You can select a stylesheet node with getElementById, querySelector, etc.

(Avoid the nonstandard <link disabled>. Setting HTMLLinkElement#disabled is fine though.)

Leave a Comment