Toggle stylesheets in JavaScript file | SoloLearn: Learn to code for FREE!


Toggle stylesheets in JavaScript file

I wanna create 4 themes for a website I'm working on for weather forecast, and i wanna call each theme when the temperature is in a certain range . So i wanna do something like this : If ( temprature is low ) { apply stylesheet that contains style of cold weather (like background of ice and blue colors..etc) } else if ( temprature is high ) { apply the stylesheet of hot weather }

5/24/2020 5:12:46 AM

Marina Khamis

6 Answers

New Answer


My approach is somewhat more basic using a single Object.assign call.


You should be able to get the link element using querySelector and then access its href attribute to change the sheet. Unfortunately, it won't work on SL afaik. But, you can try using; var stylesheet = document.querySelector('link'); stylesheet.href = "newstyles.css" There are other ways to do it depending on how you're wanting to do so. You can Google for those answers.


Marina Khamis try not to set rel attribute Read here


Here a code for dynamically load an external stylesheet in head tag, var head = document.getElementsByTagName('head')[0]; var style = document.createElement('link'); style.href = filename; style.type = 'text/css'; style.rel = 'stylesheet'; head.append(style);


Calviղ You're really brilliant ! ✨💕


The resource from “http://localhost:2525/website/themes/cold.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff It gives me this error ..