Zed
Zed

Reputation: 5921

Overriding appendChild()

I am trying to override appendChild method so that I can have control over dynamically created elements and modify them if needed before inserting into the page. I tried with this example code, just to see if it could be done:

var f = Element.prototype.appendChild;
Element.prototype.appendChild = function(){f.apply(this, arguments); };

and it works for simple examples.However, when I try to load jquery after this code:

<script> 
    var f = Element.prototype.appendChild;
    Element.prototype.appendChild = function(){f.apply(this, arguments); };
</script>

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>

I get this errors:

Uncaught TypeError: Cannot read property 'selected' of undefined jquery.min.js:4
Uncaught TypeError: Cannot read property 'appendChild' of undefined

So, why it doesn't work with jquery ? Is there a safe way to override appendChild ?

Upvotes: 1

Views: 1104

Answers (1)

lswartsenburg
lswartsenburg

Reputation: 383

It is ill advised to overwrite native functions, but if you do it than make sure you return the appended element as well to prevent problems with code that uses the returned value of the native "appendChild" function:

window.callbackFunc = function(elem, args) {
  // write some logic here
}
window.f = Element.prototype.appendChild;
Element.prototype.appendChild = function() {
    window.callbackFunc.call(this, arguments);
    return window.f.apply(this, arguments);
};

Upvotes: 2

Related Questions