Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have a direct reference to document.createElement?

Tags:

javascript

dom

When creating lots of DOM elements, document.createElement and friends can add lots of bytes and ugliness. I know I could make my own subroutine, or use innerHTML or whatever, but why can't I just do this:

var $c = document.createElement;
var newP = $c('p');

Firebug complains with this message:

"Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"

Clearly I've done something that is Not Allowed. Why isn't it? It's allowed for other things, e.g. Array.splice or Math.min.

like image 208
Rafael Avatar asked May 17 '26 04:05

Rafael


1 Answers

The way you are invoking it, causes the this value inside the createElement method to refer to the global object.

I would recommend you to simply use a function:

var $c = function (tagName) { return document.createElement(tagName); };
var newP = $c('p');

The behavior I talk can be described with an example:

var foo = 'global foo';

var obj = {
  foo: "I'm obj.foo",
  method: function () {
    return this.foo;
  }
};


var fn = obj.method;

obj.method(); // "I'm obj.foo"
fn();         // "global foo"
like image 104
Christian C. Salvadó Avatar answered May 19 '26 16:05

Christian C. Salvadó