A way to override the constructor on an HTMLElement so that I can add custom code

I am trying to somehow override the HTMLElement constructor (specifically HTMLDivElement), so that whenever any are created in any way, I can run some user logic.

Obviously this does not work:

 HTMLDivElement.prototype.constructor = function() { alert('div created!'); } 

Is there any way to remove this? Even if there was a way to get some kind of event / trigger when new elements were created (which were not part of the page’s HTML page), it would be useful.

EDIT: Maybe something we could do with Mozilla's view / disable methods to keep track of the changes?

+4
source share
6 answers

I go to hell for this:

 document.createElement = (function (fn) { return function (tagName) { var elem = fn.call(document, tagName); alert('just created a new ' + elem.tagName); return elem; }; })(document.createElement); 
+8
source

If you can use jQuery, there is a plugin called Livequery that allows you to fire events on elements not yet created. So, your example above can be written as follows:

 $("div").livequery('load', function(event) { alert('div created!'); }); 

Please note that I myself have not tried it myself, but I assume that there are no answers to this question.

Hope this helps!

+2
source

The standard way to do this is to use mutation observers.

+1
source

If you don't mind using prototype.js, this answer may help.

$ ('placeholder'). insert (new Element ("img", {id: 'something', src: myImage, onload: '(' + function () {alert ("MOO");} + ') ()'}));

0
source

I'm not sure that you can make a “hook” for every call of every new object in javascript ... but I'm sure you can create your own infrastructure where everything will be fun .. I recommend to see: http: // code. google.com/p/joose-js/

or easily go through the article: http://www.sitepen.com/blog/2008/03/18/javascript-metaclass-programming/

python has __new__ and __init__ as steps for creating classes. It would be nice to check how javascript deals with building new objects.

0
source

You do not control the change / creation of these elements? Why can't you manually do what you want after creating each item?

0
source

All Articles