Customizing a jQuery Element

Is it possible to add methods to a jQuery element?

eg:

var b = $("#uniqueID");
b.someMethod = function(){};

Update

To clarify, I'm working on a JS application that binds JSON data to local JS objects that encapsulate business logic to manage the actual underlying DOM elements. Objects currently store a link to their associated HTML / s elements. I thought that I could, in essence, combine a specific instance of a jquery element with logic by taking this link, adding the necessary methods.

+3
source share
3 answers

Well, there's nothing wrong with that. This, however, is pretty pointless. For instance:

$('body').someMethod = function(){};
console.log($('body').someMethod); // undefined

You add a new function only to this selection, and not to all selections of this element.

jQuery.fn, jQuery.prototype:

jQuery.fn.someMethod = function() {
    if (this[0].nodeName == 'body') {
        // do your function
    }

    return this; // preserve chaining
};
+2

, . , . jQuery $.fn.someMethod = function() {}, .

$.fn.someMethod = function() {}
var b = $("body"); 
b.someMethod();
+2

Or you can create a jQuery plugin. You can define a plugin this way:

$.fn.someMethod = function(options) {  
    # ... 
});

Call him with $('body').someMethod();

0
source

Source: https://habr.com/ru/post/1784674/


All Articles