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
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/
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.