Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a DOM element with jQuery

I'd like to extend a DOM element without extending all of them. That is, I'd like a custom class with its own methods and properties, but also be able to treat it as a div. E.g.

 MyClass = function(){
    this.foo = "waaa";
 }
 MyClass.prototype.changeText = function(newtext){
    // if this extended $(document.createElement("div")) something
    // like this might be possible
    this.html(newtext);
 }
 MyClass.prototype.alertFoo = function(){
    alert(this.foo);
 }

 var m = new MyClass();
 $("body").append(m);
 m.changetext();

Is this possible?

like image 997
pondermatic Avatar asked Jul 23 '09 22:07

pondermatic


2 Answers

You can make your class a child class of the jquery generated DIV element:

function MyClass (){
    this.foo = "waaa";
}
MyClass.prototype = $('<div/>');
MyClass.prototype.changeText = function(newtext){
    this.html(newtext);
}
MyClass.prototype.alertFoo = function(){
    alert(this.foo);
}

var m = new MyClass();
$("body").append(m);
m.changeText('appletree');
like image 65
user478779 Avatar answered Sep 19 '22 10:09

user478779


You could make your own object, like you are doing. Then you can use jQuery's extend method to extend the element.

like image 33
geowa4 Avatar answered Sep 20 '22 10:09

geowa4