Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking document.createElement using function prototype

Tags:

javascript

I want to hook onto the document.createElement function in such a way that, every time I create a div element, my hook will attach a "foo" attribute to the div. This is what I have currently:

<script>
    window.onload = function () {
        console.log("document loaded");
        document.prototype.createElement = function (input) {
            var div = document.createElement(input);
            console.log("createElement hook attached!");
            if (input == "div")div.foo = "bar";
            return div;
        }

        document.body.addEventListener('onready', function () {
            var div = document.createElement("div");
            console.log(div.foo);
        });

    }
</script>

When I run this in Chrome, I get an error saying

Uncaught TypeError: Cannot set property 'createElement' of undefined test.html:4 window.onload

(I changed the line number in the error message above to match my code)

What am I wrong here? How can I fix this?

like image 551
Discombobulous Avatar asked Jul 30 '12 18:07

Discombobulous


1 Answers

  • document doesn't have a .prototype, since it's an instance object and not a constructor function
  • you are calling the new document.createElement in your new function, it would end up in recursion. You need to store reference to the old one somewhere, and call that.
  • You are setting a property instead of attribute
  • This is extremely fragile thing to do and not guaranteed to work. It appears to work in chrome and firefox, but won't work in old IE

Try this

document.createElement = function(create) {
    return function() {
        var ret = create.apply(this, arguments);
        if (ret.tagName.toLowerCase() === "div") {
            ret.setAttribute("foo", "bar");
        }
        return ret;
    };
}(document.createElement)

http://jsfiddle.net/NgxaK/2/

like image 189
Esailija Avatar answered Oct 06 '22 01:10

Esailija