简体   繁体   中英

how do I override appendChild()?

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

using the code above does not seem to work.

Anyone knows?

What you might want to replace is Element.prototype.appendChild but it's probably a bad idea.

This example adds the text intercepted in 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

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM