Hooking document.createElement using function prototype

后端 未结 2 1562
暖寄归人
暖寄归人 2020-12-18 07:56

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 wh

相关标签:
2条回答
  • 2020-12-18 08:30
    • 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/

    0 讨论(0)
  • 2020-12-18 08:44

    I would suggest not overwriting existing functions, as they may be made read-only in the future. I would suggest post-processing the DOM (a quick traversal for divs is faster than intercepting the creation of every element) and/or modifying the code that inserts divs to add your attribute. Alternatively, if you really want to modify created nodes, a much better method would be Mutation Observers (HTML5):

    http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers

    This is a much better option than using the mutation events that have been deprecated in HTML4, and overwriting globals is generally considered a bad practice unless you're creating a shim or a polyfill.

    0 讨论(0)
提交回复
热议问题