If I added styles using CSSOM using insertRule , I noticed two things.
Added styles do not appear in html while viewing in Firebug.
Added styles do not work if a style tag is added (for example: moved from head to body) to another element (happens in Firefox and Chrome).
If styles are added after the tag is added, they work. They still do not show in Firebug. When adding a sheet needs to be reassigned (regenerated?), Which makes it even weirder.
In order not to show in Firebug, it may be a fad with Firebug, but regular styles that are not added dynamically are displayed.
For styles that don't work after adding, I wonder if this is the standard because it happens in Firefox and Chrome. Looking at the standards, I did not see anything about it. If I just do not understand them.
var style = document.createElement('style'), sheet = style.sheet; document.head.appendChild(style); //When line 6 is un-commented the styles work //if line 8 is also commented out. //document.querySelector('.container').appendChild(style); //Get the sheet when line 6 is un-commented sheet = style.sheet sheet.insertRule('.test{color: red}'); document.querySelector('.container').appendChild(style); //styles don't apply after the previous line
Edit for clarity:
If you add the <style></style> to the <head></head> html, you can apply styles with style.sheet.insertRule(styleString) , and the added styles will apply to the document.
If you have already added that <style></style> to <head></head> as <head><style></style></head> , and try adding <style></style> where- then, like <div><style></style></div> , all styles will be lost and will not be applied again.
This is normal?
Code stream:
Works:
- add
<style> somewhere - add styles with
style.sheet.insertRule(styleString)
Does not work:
- add
<style> somewhere - add styles with
style.sheet.insertRule(styleString) to <style> - add the same
<style> to another place
My other problem is that styles added to <style></style> do not appear in Firebug , even if they applied to the document.
Change more clarity:
If I re-add the style element without changing the stylesheet, the styles remain:
var style = document.querySelector('style'); document.head.appendChild(style);
* {color: red}
<p>Hello world</p>
But if I change the stylesheet using JS, the changes will be undone:
var style = document.querySelector('style'), sheet = style.sheet; sheet.insertRule('* {color: red}', 0); document.head.appendChild(style);
<p>Hello world</p>