Xeos Xeos - 2 years ago 83
HTML Question

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

I have a page which has

in the header that loads the CSS named
. I also have a file named
. 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
with JS and remove all the styles that were applied and then load
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 Source

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);


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download