How to extend a DOM element as a class (without jQuery)

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'); // WORKS !!!
$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.

+5
source share
4

firefox, chrome IE8 + Element.prototype, :

Element.prototype.doSomething = function() {
    alert("hello");
};

, , . , DOM , , elem.appendChild() , .


:

function $id(str) {
    this.element = document.getElementById(str);
    return element;
}

- , this , - ( this, , undefined). element ( ), .

+4

, DOM, , jQuery.

var myLib = {
   addWrapper: function ( id ) {
      return new this.WrapperClass( document.getElementById( id ) );
   },
   WrapperClass: function ( element) {
      this.element = element;
   }
};
MyLib.WrapperClass.prototype.someMethod = function() {
   alert( this.element);
}

var wrappedElement = myLib.addWrapper( 'someid' );
wrappedElement.someMethod();
+1
$id('myId').dosomething()

$id ('myId') - .

, doSomething "Element", $id, . , , , ?

0

, DOM (: ) - . - , DOM (Object, String...). .. , : http://perfectionkills.com/whats-wrong-with-extending-the-dom/

IE (IE6 & 7) , , :

Element.prototype.doSomething = function () {
    // Your code here
};

, $id . "doSomething" $id, .

:

function $id(str){
    this.element = document.getElementById(str); 
    return this;
}
0

All Articles