Jason S
Jason S

Reputation: 189686

select CSS URL dynamically via Javascript

Is there a way to add a <link rel="stylesheet" type="text/css"> with the URL dynamically-selected based on some Javascript expression evaluation?

(without using jQuery or other external library -- I want to avoid dependencies on external libraries.)

In particular I want to run some Javascript during or as a result of pageload, rather than at a later date, but I do want to make sure the CSS that has been replaced or added gets loaded as a result of running that Javascript.

Upvotes: 0

Views: 74

Answers (2)

paradise-ekpereta
paradise-ekpereta

Reputation: 21

You are welcome to try this function.

function addStylesheet(file) {
    var
        head = document.getElementsByTagName("head")[0],
        style = document.createElement("link");
    style.rel = "stylesheet";
    style.type = "text/css"; //optional
    style.href = file;
    head.appendChild(style);
}

addStylesheet("style.css");

Upvotes: 2

Toby
Toby

Reputation: 13385

Try this:

Function:

function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
}

Activate:

<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>

Upvotes: 2

Related Questions