0

Using the following script I include text and insert css into my page head at run time. However, although the css in inserted it does not take affect. Why?

(function () {

    var styleEl = document.createElement("link");
    styleEl.type = "text/css";
    styleEl.href = "/static/css/widgets.css";
    //document.getElementsByTagName('head')[0].appendChild(styleEl);
    document.head.appendChild(styleEl);


    var foo = "Goodbye World!";
    document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>');
})();
3
  • 3
    Just guessing but try adding rel="stylesheet"? Commented Mar 30, 2014 at 19:35
  • 1
    Don't use document.write! See the warning in the spec. Use DOM methods instead. Commented Mar 30, 2014 at 19:35
  • @Adrian Mitev that worked thank you! Would you like to add an answer. Commented Mar 30, 2014 at 19:39

1 Answer 1

2

You forgot to add rel="stylesheet" which is important for declaring a stylesheet <link> tag.

Here is the updated code with setting of the rel property:

(function () {
    var styleEl = document.createElement("link");
    styleEl.type = "text/css";
    styleEl.href = "/static/css/widgets.css";
    style.rel = "stylesheet";

    //document.getElementsByTagName('head')[0].appendChild(styleEl);
    document.head.appendChild(styleEl);


    var foo = "Goodbye World!";
    document.write("<p class='example-widget-container'>Inside our anomymous function foo means '" + foo + '".</p>');
})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.