Snsa90 Snsa90 - 6 months ago 12
jQuery Question

Methods that work individually for multiple elements on page

I can't find a good guide on this, but what I'm looking for here is just a push in the right direction.

Lets say I have defined a new method

Object.defineProperty(Object.prototype, 'myMethod', {
enumerable : false,
configurable: true,
value : function(args) {
var _self = this;
_self.doThis = function () {
// some functionality
}

....

return this
});


The code inside will work for let's say $('#element'), but if I apply the method to $('.elements') it will only work for the first element of the array. How do I rewrite the method to be applicable to both single elements and groups of elements?

EDIT ************************************

So I've gotten a hint that, when jQuery is available I would use jQuery.fn.extend(), but my concern is - can the approach from above be rewritten so it works for multiple elements of the same class?

Answer

I think you're confusing two very different, albeit slightly related, concepts

  • Authoring of jquery plugins, which can act on multiple selected elements
  • Adding properties/methods to the prototype of an existing object's prototype

As you seem to be concerned with DOM manipulation i'll show how to do both.


jQuery

The scope of writing jQuery plugins is vast but you should start with the basic guide to authoring plugins. You essentially add your methods to $.fn and then they work as per all other jQuery methods. As you know, a jQuery selector can select many elements, and you handle this situation by returning this.each from the plugin

$.fn.myPlugin = function() {

    return this.each(function() {
        // Do something to each element here.
    });

};

usage: $(".myElements").myPlugin();

Vanilla

If you're selecting multiple elements using vanilla javascript you're probably using one of getElementsByName or querySelector / querySelectorAll. You would need to add your new method to the return type of these methods - for getElementByName that would be NodeList and you could enumerate it within the value in the normal way

Object.defineProperty(NodeList.prototype, 'myMethod', {
    enumerable : false,
    configurable: true,
    value : function(args) {
        var _self = this;
        _self.doThis = function () {
            console.log(_self.length); // should be the number of elements
        }

        ....

        return this
});

usage: document.getElementsByName("a").myMethod();