tags:

views:

185

answers:

6

I'm trying to somehow override the constructor of HTMLElement (specifically HTMLDivElement), so that whenever any are created by whatever means, I can run some custom logic.

Obviously this doesn't work:

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

Is there a way to pull this off? Even if there was a way to get some sort of event/trigger when new elements where created (ones not part of the page's source HTML), that would be helpful.

EDIT: Maybe there is something we could do with Mozilla's watch/unwatch methods to watch for a change?

A: 

You can't do this.

Chris Pietschmann
These kinds of answers don't get us anywhere. Do you know this for a fact? Are you 100% sure this functionality has been specifically disabled for a certain reason? Are you 100% sure there is no way to hack it?
Frank Edwards
Just try the sample included in the question; it doesn't work.
Chris Pietschmann
Of course it doesn't work...I explicitly stated that in the original question. The goal is to get a code entry point when new HTML elements are instantiated, however that may be done.
Frank Edwards
+2  A: 

If you could consider using jQuery there is a plugin called Livequery which lets you trigger events on not yet created elements. So your example above could be written like this:

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

Note that I have not tried livequery myself, but I'm guessing since there are no answers to this question.

Hope it helps!

Emil Stenström
A: 

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"); } + ')()' }));

stereointeractive.com
A: 

i'm not sure you can make a 'hook' on every call of every new object in javascript... but i'm quite sure you can make your own framework where everything will be catchable.. i recommend looking at: http://code.google.com/p/joose-js/

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

python has __new__ and __init__ as steps to construct the classes.. it would be good to check how javascript is dealing with the construction of new objects.

marcell
A: 

Aren't you controlling the changing/creation of said elements? Why can't you manually do whatever you want to after each element is created?

contagious
+1  A: 

I’m going 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);
Nate
Nate...funny you would post that, it's what I had come up with after hacking around a bit...although I was too shy to post it :)
Frank Edwards