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?
document doesn't have a .prototype, since it's an instance object and not a constructor functiondocument.createElement in your new function, it would end up in recursion. You need to store reference to the old one somewhere, and call that.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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With