0

I'd like to modify all jQuery functions, which return object with DOM elements, with some additional data, so whenever I'd call jQuery functions, which return jQuery object with DOM elements, like $(selector), find, filter, etc. and would normally get a standard jQuery object:

{ 0: DOMElement1, 1: DOMElement2, 2: DOMElement3, ...}

i'd like to get a modified jQuery object instead, e.g.:

{ 0: {0: DOMElement1, num: 1}, 1: {1: DOMElement2, num: 2}, 2: {2: DOMElement3, num: 3}}

I tried to modify the $.fn.constructor:

(function($) {
   var orig = $.fn.constructor;
  
   $.fn.constructor = function(e) {
      var origApplied = orig.apply(this, arguments);
      
      console.log("Constructor called");

      var outputData = $.map( origAppliedArray, function (value, index) { return {[index]: value, num: index} });

      return outputData;
   }
    
})(jQuery)

The constructor is called every time the find or filter functions are called, but the code only returns an array with DOM elements.

How could I achieve the mentioned result?

1
  • 1
    I don't see how that is useful. Moreover it will confuse future developers that would need to work on such a project.
    – trincot
    Commented Jul 6 at 17:52

1 Answer 1

0

It would work if you would monkeypatch $.fn.init instead of $.fn.constructor.

Disclaimer: this is not advised. It will be confusing to those future developers that get to maintain your code after you. It will also break code that would be expected to work, like for instance chaining (one of the great features of jQuery) and passing arguments that are jQuery:

$("#container").append($(".copyme").clone());

Not the answer you're looking for? Browse other questions tagged or ask your own question.