Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 448
Paul Go Avatar asked Dec 23 '22 10:12

Paul Go


1 Answers

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);        
like image 52
Nate Avatar answered Mar 22 '23 22:03

Nate