Skip to content

Instantly share code, notes, and snippets.

@valueof
Created September 7, 2011 22:33
Show Gist options
  • Select an option

  • Save valueof/1202001 to your computer and use it in GitHub Desktop.

Select an option

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
// 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);
// 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);
// 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