Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a CSSStyleSheet object from a HTMLStyleElement element

Is it possible to get the CSSStyleSheet object (document.styleSheets[0]) from a HTMLStyleElement (document.createElement('style')) ?

I would like to dynamically add css rules to a not-inserted-in-the-document-yet <style> element.

like image 426
Franck Freiburger Avatar asked Jan 18 '12 16:01

Franck Freiburger


2 Answers

It is possible to get a CSSStyleSheet object from a <style> element.

var style = document.createElement('style');
document.head.appendChild(style);
var styleSheet = style.sheet // Will give you the associated CSSStyleSheet

This will only work after the <style> element has been appended to the document.

Not exceptionally well documented and very difficult to find by poking around in console.

like image 92
Jonathan MacQueen Avatar answered Oct 13 '22 21:10

Jonathan MacQueen


You can add rules before you add the style element to the document.

A couple notes-

Older IE browsers cannot add child nodes to a style element, so assign to the element's styleSheet.csstext property for them. Make sure you append the new element to the head of the document.

function addStyle(css, media1, title1){
    var el= document.createElement('style');
    el.type= 'text/css';
    if(media1) el.media= media1;
    if(title1) el.title= title1;
    if(el.styleSheet) el.styleSheet.cssText= css;//IE
    else{
        el.appendChild(document.createTextNode(css));
    }
    //return el without the next line if you want to append it later
    return document.getElementsByTagName('head')[0].appendChild(el);

}

var cs1= [
    '#yw_psq, #yw_psq h2{background-color: green; color: white;}',
    '#yw_psq_div{margin: 1ex; position: relative; text-align: center;}',
    '#ps_counter{color: white; margin: 1ex 0 0 0; text-align: center;}',
    '#pzsq_grid  button{cursor: pointer; font-size: 1.2em; width: 100%;}',
    '#delaySpan{font-weight: bold; margin-left: 1em;}'
]

addStyle(cs1.join('\n'),'screen','yw_psq');
like image 2
kennebec Avatar answered Oct 13 '22 19:10

kennebec