[RESOLVED]best way to add method to specified elements?

I have an element as <div id="#test"></div>

I want add a method Do to it, so I could call $(‘#test’).Do();

I don’t want to use universal plugin $.fn.Do(), since it will add Do method to all jquery elements.

code like

$('#test').Do = function() { ... };

won’t work,

var $div = $('#test');
$div.Do = function() { ... }

$div.Do() // this works

$('#test').Do() //this won't work

still not work as intended.

So, only workaround I can think is use .bind()/.trigger() combo, is there a better way to do this?

There is a easier way to do this. You can extend jquery itself like following.


Sorry, as I said in my first example, I don’t want to extend jquery itself, I just want to extend one DOM element.

as some one use $.extend(), it is fallen part as my second example, each time I call $(selector) it return a newly wrapped object, so the extended method attached to previous object will be lost when I call $(selector) again.

$(‘#test’) always return a new query object (extended array) instance, so you must keep function. if you want to just attach a function to a dom object, attach it the dom object, not the jquery object.

var $div = $('#test');
$div[0].Do = function() { ... }

$div[0].Do() // this works

$('#test')[0].Do() //this will work too

Leave a Reply