Possible duplicate:
In Javascript, can you extend the DOM?
I am trying to add methods and properties to an element. It is not listed as a global class. I can extend String as follows:
String.prototype.dosomething = function { ... };
I am trying to do this (this is more, this is the main):
function $id(str){
this.element = document.getElementById(str);
return element;
}
var myElem = $id('myId');
$id.prototype.dosomethig = function ( ... };
var myValue = $id('myId').dosomething(); // DOESN'T WORK !!!
I try in a different way, but always the same when I try to extend the class, it does not work. Is there any way to avoid this? I know jQuery does this, but I want to make my onwn - if they can, I can ... right?
Edit: Below 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 inside many other divs. I will try to test in IE8, after solving many other problems in my library.
source
share