How to get CSSStyleSheet object from HTMLStyleElement element

Can I get a CSSStyleSheet object ( document.styleSheets[0] ) from an HTMLStyleElement ( document.createElement('style') )?

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

+6
source share
4 answers

You can add rules before adding a style element to a document.

A few notes -

Older IE browsers cannot add child nodes to a style element, so we assign the styleSheet.csstext property to them. Make sure the new item is added to the top 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'); 
+1
source

This is to get the CSSStyleSheet object from the <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 is added to the document.

Not very well documented and very difficult to find by orienting yourself in the console.

+2
source

This is how I usually do mith my javascript to create a new style and for its mycss (instead of the HTMLStyleElement returned by appendChild ):

 document.head.appendChild(document.createElement("style")).setAttribute("type", "text/css"); var mycss = document.styleSheets[document.styleSheets.length-1]; 

This is how I add style rules to it:

 mycss.insertRule("css, selectors { cool: styles; and: stuff; }", mycss.cssRules.length); 

Hope this helps.

+1
source

If you have access to an element to be inserted, you can add style information to it, just like any other element. After the element is inserted, the browser will translate the page and pick up any relevant CSS rules that apply. You do not need access to the stylesheet to style the element, you just need access to the element.

0
source

Source: https://habr.com/ru/post/906323/


All Articles