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.

Categories: BlogJavaScript

Leave a Reply

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