Reputation: 2632
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?
Upvotes: 4
Views: 3119
Reputation: 19030
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);
Upvotes: 9
Reputation: 10721
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?
Upvotes: 0
Reputation: 1402
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.
Upvotes: 0
Reputation: 13446
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"); } + ')()' }));
Upvotes: 0
Reputation: 14106
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!
Upvotes: 2