How to override appendChild ()?

appendChild = function(message) { console.log("intercepted!"); } 

using the above code does not work.

Somebody knows?

+7
source share
2 answers

What you want to replace is Element.prototype.appendChild , but this is probably a bad idea.

This example adds intercepted text to the inserted element:

 var f = Element.prototype.appendChild; Element.prototype.appendChild = function(){f.apply(this, arguments);arguments[0].innerHTML="!Intercepted!"; }; document.body.appendChild(document.createElement("div")); 

Demonstration

+13
source

It is not recommended that you rewrite your own functions, but if you do, make sure you also return the added item to prevent problems with code that uses the return value of the appendChild native 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); }; 
+2
source

All Articles