hsz
hsz

Reputation: 152216

Extend jQuery specified object with custom function

With

$.fn.customFunction = function(){};

we can extend whole jQuery and use it with:

$('body').customFunction();

Is it possible to extend only specified element like:

var elem = $('#elem');
    elem.fn.customFunction = function(){};

elem.customFunction();      // function is called
$('body').customFunction(); // this call should cause error

Upvotes: 1

Views: 112

Answers (2)

tckmn
tckmn

Reputation: 59283

var elem = $('#elem');
elem.customFunction = function(){};

Remove the fn.

This can also be used on normal elements (or any other object, for that matter):

var elem = document.getElementById('elem')
elem.customFunction = function(){}

Upvotes: 5

lonesomeday
lonesomeday

Reputation: 237865

You want the function to be available on that one object? That's easy enough:

var elem = $('#elem');
elem.customFunction = function() {};

Note that this will only work on that one function. This, for instance, will not work:

$('#elem').customFunction();

This is because the jQuery constructor makes a new object every time it is run; it does not reuse objects.

Upvotes: 5

Related Questions