Created
September 7, 2011 22:33
-
-
Save valueof/1202001 to your computer and use it in GitHub Desktop.
"Unexpected call to method or property access" when trying to create a style tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Problem | |
| var css = 'a.check-css { color: #f00; }'; | |
| var el = document.createElement('style'); | |
| el.setAttribute('type', 'text/css'); | |
| el.appendChild(document.createTextNode(css)); // Unexpected call to method or property access. | |
| document.getElementsByTagName('head')[0].appendChild(el); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Solution | |
| var style = document.createElement('style'); | |
| style.setAttribute('type', 'text/css'); | |
| if (style.styleSheet) { // Internet Explorer only | |
| style.styleSheet.cssText = css; | |
| } else { | |
| style.appendChild(document.createTextNode(css)); | |
| } | |
| head.appendChild(style); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Test | |
| injectCss("a.css-check { color: #f00; }"); | |
| // Add a test A tag with class css-check | |
| var el = this.document.createElement('a'); | |
| el.className = 'css-check'; | |
| this.document.getElementsByTagName('body')[0].appendChild(el); | |
| // Check its computed style | |
| var style; | |
| if (el.currentStyle) {// Internet Explorer only | |
| style = el.currentStyle; | |
| assertEqual(style.color, '#f00'); | |
| } else { | |
| style = this.document.defaultView.getComputedStyle(el, null); | |
| assertEqual(style.color, 'rgb(255, 0, 0)'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment