Embedding a Style Sheet

Sometimes you may want to embed a style sheet in a new <style> element rather than including or importing one. The simplest way to embed a style sheet is to create a Text node containing all the rules and then insert it into the <style> with appendChild().

snippet
function embedSheet(text) {
    var element = document.createElement("style");
    element.type = "text/css";
    document.getElementsByTagName("head")[0].appendChild(element);
    text = document.createTextNode(text);
    try {
        element.appendChild(text);
    } catch (e) {
        element.styleSheet.cssText = text.data;
    }
}

Now let’s test embedSheet() by passing in a couple of rules that will change the sprite from blue to red.

embedSheet("ul.blue a {background-image:url(images/fuchsia.gif);} div#running {left:500px;}");
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +