jQuery .selector property removed, workaround?
Asked Answered
K

1

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?

Kandis answered 30/5, 2013 at 12:52 Comment(5)
I'm not even sure where it would be, but you can search through the jQuery 1.8 source tree for it: github.com/jquery/jquery/tree/1.8-stableValvular
There was a discussion before. See if it helps.. [Alternative to .selector property now that it is removed in jQuery 1.9][1] [1]: #14965260Outcrop
#500746Midst
Just out of curiosity, why do you need the selector?Valvular
You can trace the history of this property's deprecation in this issue.Interflow
V
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."

Volkan answered 30/5, 2013 at 12:59 Comment(5)
Yeah, but $('.theClassISelected').myplugin($('.theClassIsSelected')); looks even worse to me.Kandis
@Jaxo agreed... it's ugly, I don't see another way to get access to the selector though :/Volkan
@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!Kandis
@Jaxo Pass a string instead of a jQuery object.Apartment
@Jaxo i didn't say you downvoted this answer, i was speaking to the anonymous downvoter ;)Shaveling

© 2022 - 2024 — McMap. All rights reserved.