Possible Duplicate:
In Javascript, can you extend the DOM?
I’m trying to add methods and properties to the Element. It is not listed as a global class. I can extend String like this:
String.prototype.dosomething = function { ... };
I try like this (it’s bigger, this is the basic):
function $id(str){
this.element = document.getElementById(str);
return element;
}
var myElem = $id('myId'); // WORKS !!!
$id.prototype.dosomethig = function ( ... };
var myValue = $id('myId').dosomething(); // DOESN'T WORK !!!
I try in other ways but the point it’s always the same, when I try to extend the class, it doesn’t work. Is there a way to avoid this? I know jQuery do this, but I want to do my onwn – if they can, I can… right?
Edit:
Below a code already working in Safari and Firefox…
Element.prototype.pos = function(){
var curleft = this.offsetLeft;
var curtop = this.offsetTop;
var scrleft = this.scrollLeft;
var scrtop = this.scrollTop;
var pElement = pElementScr = this.offsetParent
while(pElement){
curleft += pElement.offsetLeft;
curtop += pElement.offsetTop;
pElement = pElement.offsetParent;
}
while(pElementScr){
scrleft += pElementScr.scrollLeft;
scrtop += pElementScr.scrollTop;
pElementScr = pElementScr.offsetParent;
}
return {x:this.offsetLeft, y:this.offsetTop};
}
It gives the position of a div even inner of a lot of other divs. I’ll try to test in IE8, after solve a lot of other issues of my library.
In firefox, chrome and IE8+ elements inherit from
Element.prototypeso you must do:Extending host prototypes is very fragile and not recommended but should be fine if you are just playing around. The main reason is that DOM specification doesn’t specify prototypal implementations but just interfaces,
elem.appendChild()should just work, it doesn’t have to be in some prototype.This:
Only worked because of the undesired behavior that
thisrefers to the global object when a function is invoked without any object context (It should just flat out throw an error at the mere sight ofthis, though strict mode somewhat fixes this by setting it toundefined). You are making a global variableelement(since property assignments to the global object become global variables) and then returning the global variable.