Paul Gordon
Paul Gordon

Reputation: 2632

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

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

Answers (6)

Ben Davis
Ben Davis

Reputation: 13820

The standard way to do this is to use Mutation Observers

Upvotes: 1

Nate
Nate

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

helloandre
helloandre

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

marcell
marcell

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

stereoscott
stereoscott

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

Emil Stenström
Emil Stenström

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

Related Questions