Object cannot be created in this context, Code: 9

We’d been running into this wonderfully informative error message from Firefox recently and finally found some time to track it down. If you’re running into it, check your code to see if you’re trying to grab a reference to the computed style on a null reference. So code like this:

function foo() {
  var n = dojo.byId("a-bad-id");
  console.log(dojo.getComputedStyle(n));
}

Here’s a simple repro case. If you’re using dojo, you can tickle this a number of ways as a bunch of functions use dojo.getComputedStyle under the hood, like marginBox, contentBox, style when used as a getter, and others.

So the moral of the story: make sure you’re passing a valid node reference or a valid node id to functions that work with computedStyle objects.

2 responses

  1. Thank you! This had me stumped, as it was inconsistently happening when invoking the same function from different spots on the page. Your explanation directed me right at the problem with my script.

    Interestingly — IE7 throws a “‘style’ is null or not an object” error in this scenario. Looking at the two errors together really makes a lot of sense now that I know the root cause.

  2. Thank you dude!
    You saved my life… :)

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.