Switch several CSS stylesheets

Function JavaScript 1 revisions 159 a year ago a year ago
function setTheme(theme) {
    var styles = document.querySelectorAll('link[rel="stylesheet"]');
    styles.forEach(function(style) {
        var styleTheme = style.getAttribute('data-theme');
        style.disabled = styleTheme && styleTheme !== theme;

This function uses data-theme to identify theme stylesheets, and then enables a theme and disables all others.

Use like:

<link rel="stylesheet" type="text/css" href="light.css" data-theme="light" disabled>
<link rel="stylesheet" type="text/css" href="dark.css" data-theme="dark">
<link rel="stylesheet" type="text/css" href="something.css">

and then in JavaScript, whenever you want to switch:


This enables the light theme, and disables the dark one. The stylesheet without data-theme is kept untouched.