1

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh my, I was blinded with prototype. Thanks !
Ok, and if I would like to reuse this function later with creating object again ?\
The jQuery way would be to have the function exist on all elements, but only do anything on the one you mean.
5
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(){}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.