Skip to content Skip to sidebar Skip to footer

Why Can't I Have A Direct Reference To Document.createelement?

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

Solution 1:

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;
  }
};


varfn = obj.method;

obj.method(); // "I'm obj.foo"fn();         // "global foo"

Post a Comment for "Why Can't I Have A Direct Reference To Document.createelement?"