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?

1

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

3 Comments

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 It works in IE8 without adding it to the document/header. I append it after.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.