When using CSSOM to add styles with insertRule
, I've made an interesting observation.
The added styles do not show up in Firebug when viewing the HTML.
If the style tag is moved from head to body or appended to another element, the added styles do not work (this occurs in Firefox and Chrome).
However, if the styles are added after the tag is appended, they do work. But still, they do not appear in Firebug. Reassigning (or re-getting) the sheet when appending makes this process even stranger.
It's possible that the issue of not showing in Firebug is specific to Firebug itself, as regular static styles correctly display.
As for the problem of styles not working after being appended, I wonder if this behavior is standard since it happens across multiple browsers. Upon further inspection of the standards, I could not find any mention of this scenario unless my understanding is flawed.
var style = document.createElement('style'),
sheet = style.sheet;
document.head.appendChild(style);
// Uncomment line 6 for styles to work
// Comment out line 8
// document.querySelector('.container').appendChild(style);
// Get the sheet when line 6 is uncommented
sheet = style.sheet
sheet.insertRule('.test{color: red}');
document.querySelector('.container').appendChild(style);
// Styles do not apply after the previous line
Edit for better understanding:
If you append a <style></style>
tag to the <head></head>
of HTML and then apply styles using
style.sheet.insertRule(styleString)
, the added styles will be applied throughout the document.
However, if you have already appended the <style></style>
tag to the <head></head>
like
<head><style></style></head>
, and then try to append <style></style>
somewhere else such as <div><style></style></div>
, all styles will be lost and won't apply again.
Is this normal?
The code flow:
Works:
- Append
<style>
anywhere - Add styles using
style.sheet.insertRule(styleString)
Doesn't work:
- Append
<style>
anywhere - Add styles using
tostyle.sheet.insertRule(styleString)
<style>
- Re-append the same
<style>
elsewhere
Additionally, it seems that styles added to <style></style>
do not appear in Firebug, even though they are applied to the document.
Further clarification:
If I reappend the style
element without modifying the stylesheet, the styles remain intact:
var style = document.querySelector('style');
document.head.appendChild(style);
* {color: red}
<p>Hello world</p>
However, if the stylesheet has been altered with JavaScript, those changes are reversed:
var style = document.querySelector('style'),
sheet = style.sheet;
sheet.insertRule('* {color: red}', 0);
document.head.appendChild(style); // If you comment this line out, it works.
/* CSS rules inserted through JS */
<p>Hello world</p>