0

The code below throws the error Error: Unexpected call to method or property access when I create a style elemnt and attempt to append the code to it:

//This is OK
var styleElement = document.createElement("style");

//This is OK
styleElement.type = "text/css";

//THIS THROWS THE ERROR
styleElement.appendChild(document.createTextNode("a { color: red; }"));

What am I doing wrong?

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • Also related: http://stackoverflow.com/questions/9250386/trying-to-add-style-tag-using-javascript-innerhtml-in-ie8 – Ian Sep 16 '14 at 20:13

1 Answers1

2

You have to do it this way in older versions of IE (6-8):

styleElement.styleSheet.cssText = "a { color: red; }";

You can do something like this to support multiple browsers/versions:

var style = "a { color: red; }";

if(styleElement.styleSheet) styleElement.styleSheet.cssText = style;
else styleElement.appendChild(document.createTextNode(style));
Peter
  • 12,541
  • 3
  • 34
  • 39
  • Not sure if I'm right, but I think setting `.styleSheet.cssText` has to be done **after** the element is appended to the document (from what I found in other SO questions). Either way, this is the right answer – Ian Sep 16 '14 at 19:11
  • @Ian It works in IE8 without adding it to the document/header. I append it after. – Don Rhummy Sep 16 '14 at 19:30
  • To help with issues that may be found: YES APPEND FIRST THEN ADD TEXT!! I discovered this in my app i'm working on. Setting the css text first before appending will cause strange behavior and possible remove qualifiers from your rules. This showed up for me running IE11 in compatibility IE8 mode. Setting the text before appending to the head caused all !important modifiers associated with background properties to be removed. Horrifyingly difficult to debug and find out such a simple thing was the issue. – Diniden Aug 05 '15 at 20:50