Working with the CSSstyleSheet
API
- Changing the selectorText -
Test 4 - adapting the script
In the tests 1/2/3 it looks like the initial selectorText
is repeated after the update (except the explicit javascript driven
.otherClass
change). - Aha, that is the pitfall!
The let myRules = ...
definition (pointing to the initial values of the selectorText
) is a global variable if it's not
inside a function, and when recalled in the update function it's using exactly the same values.
When defining the let myRules = ...
anew in the update function, the suffering should have been suffered.
See what happens!
Testing a style update
- Use the Developer Tool of the browser and go to the 2nd
<style>
block in the<head>
. - Click right and "Edit as HTML".
- Delete the word
main
of the selector rulemain code { ... }
- Delete the whole style rule
.testbox-1 { background: turquoise; color: black }
and leave the editor by clicking somewhere in the Developer Pane outside the editor box. - Then use the button to update the selectorText via the
CSSStyleSheet
API.
This is ".testbox1"This is ".testbox2"
The initial selectorText for each style rule of the 2nd style block is:
*
main code
.testbox1
.testbox2
The updated selectorText for each style rule of the 2nd style block is:
*
code
.otherClass
Results
- Firefox, Chrome, Opera on desktop: working as expected
. No difference online/offline.
- But:
IE-11 is not working as expected (in version 3). - Now the MDN-documentation for
cssRule.selectorText says:
- The "cssRule.selectorText" is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see Using dynamic styling information.
- IE-11 is one of the browsers with the "readonly" property! See the javascript of this page and the Console of IE-11:
IE-11 can find the ".testbox2" ("yep" in the console), but the change into ".otherClass" has no effect (afterwards still ".testbox2" in the console).
Conclusion
- The CodePen was not telling the truth, the whole truth and nothing but the truth.
- Firefox, Chrome and Opera are fine.
- Something to do for IE-11 ...