evfwcqcg
evfwcqcg

Reputation: 16335

How to add new methods to the jQuery object?

Is there some way to add methods to jQuery's objects?

For example, I have jQuery object

a = $('div')

I'd like that every object which was assigned like that, would have particular method (doSomething()) so I could invoke it like

a = $('.foo')
a.doSomething()

b = $('.bar')
b.doSomething()

Upvotes: 17

Views: 9331

Answers (2)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

add it like

$.fn.doSomething = function(data){
    // data is the argument passed to doSomething
    return this.each(function(){
       var elem = $(this);
       //perform operation on elem
       // like to change background color use
       elem.css('background-color','red');

    });
}

Upvotes: 1

kapa
kapa

Reputation: 78671

You have to add your function to the $.fn namespace. Please note that inside the function, this will refer to the jQuery object, not a DOM object.

$.fn.doSomething = function () {
    this.css('color', 'red');
};

$('#retk').doSomething();

jsFiddle Demo

Please read about writing jQuery plugins for additional guidelines.

Upvotes: 20

Related Questions