How to Switch Between Multiple CSS Stylesheets using JavaScript?
To switch between multiple CSS stylesheets using JavaScript, the href
attribute of the <link>
element can be changed dynamically
in the HTML document that links to the stylesheets.
<link id="theme" rel="stylesheet" type="text/css" href="light.css" />
The "href" attribute specifies the file location of the CSS file. By altering this tag, we can add new CSS to the website. The implementation can be done using any of the following methods.
Example 1: When you want to make a switch or toggle button, to toggle the CSS. It switches between the values depending upon the currently active value.
<!DOCTYPE html>
<html>
<head>
<!-- Add the stylesheet -->
<link id="theme" rel="stylesheet"
type="text/css" href="light.css" />
</head>
<body>
<h2>Changing Style Sheets</h2>
<br />
Click the button below to switch
between light and dark themes.<br />
<button onclick="toggleTheme()">Switch</button>
<script>
function toggleTheme() {
// Select the <link> element
let theme = document.getElementById('theme');
// Toggle between light.css and dark.css
if (theme.getAttribute('href') == 'light.css') {
theme.setAttribute('href', 'dark.css');
} else {
theme.setAttribute('href', 'light.css');
}
}
</script>
</body>
</html>
/* dark.css */
body {
background-color: black;
color: white;
}
/* light.css */
body {
background-color: white;
color: black;
}
Output:

Example 2: When you want to select from multiple style sheets. The value for the "href" attribute is passed to the function call itself.
Prerequisite: Prepare all the style sheets in a folder.
<!DOCTYPE html>
<html>
<head>
<!-- Add the style sheet. -->
<link id="theme" rel="stylesheet" type="text/css" href="light.css" />
<script>
function toggleTheme(value) {
// Obtain the name of stylesheet
// as a parameter and set it
// using href attribute.
let sheets = document
.getElementsByTagName('link');
sheets[0].href = value;
}
</script>
</head>
<body>
<h2>Changing Style Sheets</h2>
<br />
Switch between multiple themes
using the buttons below.<br />
<button onclick="toggleTheme('light.css')">
Light
</button>
<button onclick="toggleTheme('dark.css')">
Dark
</button>
<button onclick="toggleTheme('geeky.css')">
Geeky
</button>
<button onclick="toggleTheme('aquatic.css')">
Aquatic
</button>
</body>
</html>
/* light.css */
body {
background-color: white;
color: black;
}
/* dark.css */
body {
background-color: black;
color: white;
}
/* aquatic.css */
body {
background-color: #4DB6AC;
color: #004D40;
}
/* geeky.css */
body {
background-color: #282C34;
color: #61DAFB;
}
Output:

Note: The corresponding CSS files with required names should be available and the path to them should be passed using the function. The files specified here are placed in the same folder of the HTML file so that the path resembles 'light.css'.