Xeos Xeos - 7 months ago 15
HTML Question

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

I have a page which has

<link>
in the header that loads the CSS named
light.css
. I also have a file named
dark.css
. I want a button to swap the style of the page all together (there are 40 selectors used in css file and some do not match in two files).

How can I remove reference to
light.css
with JS and remove all the styles that were applied and then load
dark.css
and apply all the styles from that? I can't simply reset all of the elements, since some of the styles are applied through different css files and some are dynamically generated by JS. Is there a simple, yet effective way to do that without reloading the page? Vanilla JS is preferable, however I will use jQuery for later processing anyways, so jQ is also fine.

Answer

From Omnimint:

The Javascript:

function changeCSS(cssFile, cssLinkIndex) {

    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link");
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("type", "text/css");
    newlink.setAttribute("href", cssFile);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}

The HTML:

<html>
    <head>
        <title>Changing CSS</title>
        <link rel="stylesheet" type="text/css" href="positive.css"/>
    </head>
    <body>
        <a href="#" onclick="changeCSS('positive.css', 0);">STYLE 1</a> 
        <a href="#" onclick="changeCSS('negative.css', 0);">STYLE 2</a>
    </body>
</html>

For simplicity, I used inline javascript. In production you would want to use unobtrusive event listeners.