My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, February 12, 2007

Could I change a native function ?

Just a quick post about how to modify a document (and others generic objects) native methods.

// basic example
document.createElement = (function(createElement, Element){
return function(nodeName){
var element, key;
try{element = createElement(nodeName)}
catch(e){element =, nodeName)};
for(key in Element)
element[key] = Element[key];
return element;
})(document.createElement, {});

What's that ?
... a really simple way to extend with your defined object each element created using document.createElement function.
This is an example with useful comments (I hope)

// redefine document.createElement native function
// using anonymous function
document.createElement = (
// original document.createElementFunction

// object used to extend created elements

// new document.createElement function
return function(

// type of element (div, p, link, style ... )

// element and key to loop over object
var element, key;

// IE like this
try{element = createElement(nodeName)}

// FireFox like that
catch(e){element =, nodeName)};

// loop over Element
for(key in Element)

// and assign each method to new element
element[key] = Element[key];

// return created element
return element;
// send to anonymous, the original function

// send object used to extend created elements too
// read firstChild node
return this.firstChild.nodeValue

// write text into node

// basic example
onload = function(){
var div = document.createElement("div");
div.write("Hello World !!!");
alert(; // Hello World !!!

That's all, and this method is only a basic native method override example, have fun with JavaScript :-)

1 comment:

qui.nguyen said...

So cool script. Could you tell me how can you write that script, my mean is where is the knowledge you obtain to able to write that script? I try research in many places, but only find the solution with your script. Thank you very much.