JavaScript – Create Stylesheet

At times you may need to add a dynamically created stylesheet to a page via JavaScript. You can do just that with the following function:

/**
 * Creates a STYLE element with the specified content.
 * @param  {string} content  The stylesheet content.
 * @return {!Element}  The created STYLE element.
 */
function createStyleSheet(content) {
    var style = document.createElement('style');
    var styleSheet = style.styleSheet;
    if (styleSheet) {
        styleSheet.cssText = content;
    }
    else {
        style.appendChild(document.createTextNode(content));
    }
    style.type = 'text/css';
    return style;
}

It is important to note that the above function simply create the STYLE tag with the specified stylesheet content. It does not add it to the head or anywhere else in the document. Also, it is important to note that some versions of IE limit you to 32 stylesheets per page so multiple uses of this function are not encouraged unless you know your visitors will not use such a version of IE.

Leave a Reply

Your email address will not be published. Required fields are marked *


four + = 10

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">