Sometimes, we want to replace CSS file on the fly and apply the new style to the page with JavaScript.
In this article, we’ll look at how to replace CSS file on the fly and apply the new style to the page with JavaScript.
How to replace CSS file on the fly and apply the new style to the page with JavaScript?
To replace CSS file on the fly and apply the new style to the page with JavaScript, we can set the media attribute of the link element.
For instance, we write
<link rel="stylesheet" href="main.css" />
<link rel="stylesheet" href="light.css" media="none" id="light" />
<link rel="stylesheet" href="dark.css" media="none" id="dark" />
to add a few style sheets.
Then we write
const enableStylesheet = (node) => {
node.media = "";
};
const disableStylesheet = (node) => {
node.media = "none";
};
to define the enableStylesheet and disableStylesheet functions.
We set node.media to an empty string in enableStylesheet to enable the stylesheet.
And we set node.media to 'none' in disableStylesheet to disable the stylesheet.
Conclusion
To replace CSS file on the fly and apply the new style to the page with JavaScript, we can set the media attribute of the link element.