tags:

views:

244

answers:

4

The native document.createElement() is silly-stupid (it takes only a tag name and no attributes). How come I can't override it? How come this doesn't work?

var originalFunction = document.createElement;

document.createElement = function(tag, attributes) {
    var element = originalFunction(tag);

    if (attributes) {
        for (var attribute in attributes) {
            element.setAttribute(attribute, attributes[attribute]);
        }
    }

    return element;
};

The problem is that browsers blow up when you try to replace a native function. Since document is not a JavaScript primitive, you can't create a prototype for it either. WTF.

A: 

I'm not a javascript genius but doesn't that require some prototype calls?

Kyle
+1  A: 

As far as I know you cannot override native methods for security reasons. For non-native methods it's no problem at all.

nickyt
+3  A: 

FWIW (informational): you can override "native" methods, in some cases, and in some browsers at least. Firefox lets me do this:

document.createElement = function(f) { alert(f); };

Which then does as you expect when invoked. But your whole block of code above throws an error, at least via Firebug.

Philosophically, you should be able to do this. You can certainly, say, redefine methods on the Array object, etc. But the window (DOM) methods are not covered by ECMAScript, and so they're probably allowed to be implementation-dependent. And of course, they are this way for security reasons.

quixoto
+1  A: 

Why not just use the method in your own function- write it the way you want, and never write document.createElement again....

    document.create= function(tag, parent, attributes){
     tag= document.createElement(tag);
     for(var p in attributes){
      if(p== 'css') tag.style.cssText= attributes.css;
      else if(p== 'text') tag.appendChild(document.createTextNode(attributes.text));
      else tag[p]= attributes[p];

     }
    if(parent) parent.appendChild(tag);
     return tag;
    }

document.create('p',document.body,{css:'font-style:italic',className:'important',title:'title',
text:'whatever text you like'});
kennebec