Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding native function?

Tags:

javascript

dom

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.

like image 844
JamesBrownIsDead Avatar asked Feb 27 '10 03:02

JamesBrownIsDead


1 Answers

As far as I can tell the problem is that a call to the document.createElement() function even when referenced has to be from the document. So modify your code:

var element = originalFunction.call(document, tag);
like image 176
bosko Avatar answered Oct 19 '22 15:10

bosko