8

I'm trying to get the selector used to call the current script, but of course the property I need was removed for some reason.

Is there a workaround for this? Here's basically what I want to accomplish:

(function($) {
    $.fn.myplugin = function(options) {
        return this.each(function() {
            console.log($(this).selector);
        });
    }
}(jQuery));

//Somwehere else:

$('.theClassISelected').myplugin();  //Should console.log('.theClassISelected')

I need to see .theClassISelected (or some form of the original selector I used to call the function) in the console, but since the selector property has been removed from jQuery, it doesn't possible anymore.

I don't understand why it was removed - I've Googled this problem for a while now and all I see are StackOverflow answers from 2011-2012 recommending the selector property. I guess it was useful at some point, but not anymore?

Scott
  • 5,338
  • 5
  • 45
  • 70
  • I'm not even sure where it would be, but you can search through the jQuery 1.8 source tree for it: https://github.com/jquery/jquery/tree/1.8-stable – Blender May 30 '13 at 12:57
  • 1
    There was a discussion before. See if it helps.. [Alternative to .selector property now that it is removed in jQuery 1.9][1] [1]: http://stackoverflow.com/questions/14964760/alternative-to-selector-property-now-that-it-is-removed-in-jquery-1-9 – Kazi Sabbir Ibna Ataur May 30 '13 at 12:58
  • 1
    http://stackoverflow.com/questions/500246/how-do-i-get-a-jquery-selectors-expression-as-text/501316#501316 – billyonecan May 30 '13 at 13:07
  • Just out of curiosity, why do you need the selector? – Blender May 30 '13 at 16:58
  • You can trace the history of this property's deprecation [in this issue](https://github.com/jquery/jquery/issues/1908). – thdoan Jun 15 '17 at 02:54

1 Answers1

4

From the jQuery documentation:

Plugins that need to use a selector should have the caller pass in the selector as part of the plugin's arguments during initialization.

http://api.jquery.com/selector/

As an aside, the docs also mention that the selector property wasn't reliable since "since subsequent traversal methods may have changed the set."

cfs
  • 10,610
  • 3
  • 30
  • 43
  • Yeah, but `$('.theClassISelected').myplugin($('.theClassIsSelected'));` looks even worse to me. – Scott May 30 '13 at 13:00
  • 1
    @Jaxo agreed... it's ugly, I don't see another way to get access to the selector though :/ – cfs May 30 '13 at 13:02
  • @roasted and cfs I didn't downvote, no idea where it came from. StackOverflow said "one new answer to this post", and I clicked it to find the post insta-downvoted. Counter-upvoted! – Scott May 30 '13 at 13:04
  • 4
    @Jaxo Pass a string instead of a jQuery object. – Ram May 30 '13 at 13:04
  • @Jaxo i didn't say you downvoted this answer, i was speaking to the anonymous downvoter ;) – A. Wolff May 30 '13 at 13:05