Theofanis Pantelides Theofanis Pantelides - 9 months ago 50
Javascript Question

(Override || Extend) Javascript Method

I want to change the method DomElement.appendChild() to work differently when applied on an Object that I have created:

// using MooTools;
var domElement = new Class({...});

var MyObject = new domElement(...);

$(document).appendChild(MyObject); // Error

// I want to add to (extend) appendChild, to do something specific, when:
alert(MyObject instanceof domElement); // true

I could do this by modifying the mootools.js, but I want to avoid this at all costs, because I am certain one day, some other developer will overwrite the js file with an updated version, and I will be imprisoned for murder.

Please, keep me out of jail!


I dont know about MooTools, but there is a simple way in native JS to do this..

    var orgAppendChild = document.appendChild;  
    document.appendChild = localAppendHandler;

    var domElement = new Class({...});
    var MyObject = new domElement(...);
    // document.appendChild(MyObject);

     var ss = document.createElement('tr'); 
document.appendChild (ss);

    function localAppendHandler(MyObject)
     if (MyObject instanceof domElement)
		UrCustomRoutine(MyObject )


    function UrCustomRoutine(MyObject ){
	//your custom routine

Hope this helps

Update: From your further explanation (handling appendChild of any DOM element), i understand that there is no generic way of defining local hanlders to trap the event.

But there is a workaround (this is very ugly i know). Means you have to define a LocalHandler for the DOM element before you are goin to use the appendChild .

Before doing this document.getElementByID('divTarget').appendChild()

you have to reassign the localhandler to the element you need to access

    orgAppendChild = document.getElementById('divTarget').appendChild;  
    document.getElementById('divTarget').appendChild = localAppendHandler;
    var sss = document.createElement('table'); 

Another Alternative: If you wanted to keep it simple, i suggest this alternate way. Create AppendChild local method which accepts object and the node name as param.

    function AppendChild(MyObject ,Node)
           if (MyObject instanceof domElement)
               //your custom routine
           else if (Node=="" && (MyObject instanceof domElement==false))
           else if (Node!="" && (MyObject instanceof domElement==false))
               eval( "document.getElementById('" + Node + "').appendChild(MyObject);");



  1. If you wanted to append DOM element to document

  2. If you wanted to append DOM element inside other container

  3. If you wanted to process your custom object


this is the best way to do this.