1

So I have a jQuery function:

$("#el01").myFunc();
$("#el02").myFunc();
$("#el03").myFunc();

Is there simple way to find out which elements in the DOM have been bound to that function, without having to manually store references in an object or array?

Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55
  • Kind of [relevant](http://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object) but it's opposite. I don't think jQuery keeps track of that, but I'm searching. – Sterling Archer Nov 24 '15 at 21:11

2 Answers2

0

There are a couple of common options!

A common approach is to decorate the elements with a class, or data- attribute if you touch them (leave a footprint), that way, you can look them up with a selector:

$('.myFuncified')...

Or you can keep tabs of them in an object to store state (which you said you didn't want to do... that's fair enough).

But there is not a way of finding out that you've touched an element unless you leave some footprint.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Ahh, I see. I thought there might be a way to loop over the dom and see if anything had been bound... or maybe if what was bound to a function was recorded in the function's prototype somehow. Adding classes is simple enough! – Benjamin Allison Nov 24 '15 at 21:14
0

The core issue here is what is myFunc? That is the true culprit here. Could easily modify it to know what it was acting on.

(function(){
    var stored = $.myStored = [];
    $.fn.myFunc = function(args){
        this.each(function(){ stored.push(this); });
    }
})()

And now you can easily access the stored elements. There are of course several ways to accomplish this, but the idea is that the prototype function must record the elements it encounters some how.

In your example, you could do this with the above snippet

    (function(){
        var stored = $.myStored = [];
        $.fn.myFunc = function(args){
            this.each(function(){ stored.push(this); });
        }
    })()

$("#el01").myFunc();
    $("#el02").myFunc();
    $("#el03").myFunc();
    $($.myStored).css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="el01">el01</div>
<div id="el02">el02</div>
<div id="el03">el03</div>
Travis J
  • 81,153
  • 41
  • 202
  • 273