Reputation: 4675
I am making a jQuery plugin, and I was wondering if there was a way that I could find the selector that the user uses to apply the plugin. For example, if the user selects this:
$(".myClass").pluginName();
Then the plugin will return myClass
, which can then be used later. Is there a way I can do this?
Upvotes: 5
Views: 110
Reputation: 47101
Suppose this is your selection :
var $selection = $('a, i');
If you want to get the selector, just use the selector
property :
var selector = $selection.selector;
In this case, the value of the selector
variable would be the string a, i
.
While the selector
property is included in jQuery 1.11.0 and jQuery 2.1.3, it appears to be missing from jQuery 3.0.0 alpha1. This is probably why :
The
.selector
property was deprecated in jQuery 1.7 and is only maintained to the extent needed for supporting.live()
in the jQuery Migrate plugin. It may be removed without notice in a future version.
If you can think of a good reason why this feature should stay in the jQuery core, you might want to make an appeal to the jQuery dev team and request they change their decision to remove the feature.
Upvotes: 4
Reputation: 12214
Inspecting the jQuery object in the debugger, it has an attribute selector
that contains the selector used to create the set. I don't know if this is public API that you can count on remaining available in future releases or if this is an implementation detail that may change without warning.
Like the other commenters, I question the need to reference the selector. In your plugin you can simply iterate through all of the selected elements without performing the search through the DOM again. Just use this.each()
in your plugin.
Upvotes: 1