Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get original selector

I'm in the middle of writing a plugin and I'd like to be able to get the original selector that jQuery used to create the object.

So if you wanted to apply something like .siblings() you could get all the siblings of that type, whether it looks up siblings of a certain class or siblings of a certain element type.

  • jQuery('div')'div'
  • jQuery(jQuery('div'))'[jQuery] object' // would require recursively finding the selector of this
  • jQuery('#elment')'#element'
  • jQuery('.class')'.class'
like image 589
vol7ron Avatar asked Aug 27 '11 03:08

vol7ron


3 Answers

Just access the jQuery object's selector property:

console.log($("div").selector); // 'div'
console.log($("#foo").selector); // '#foo'
like image 79
karim79 Avatar answered Sep 23 '22 06:09

karim79


This no longer seems possible... '.selector' was removed in version 3 and jquery instead recommends passing in the selector twice.

https://api.jquery.com/selector/....

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. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set. Plugins that need to use a selector string within their plugin can require it as a parameter of the method. For example, a "foo" plugin could be written as $.fn.foo = function( selector, options ) { /* plugin code goes here */ };, and the person using the plugin would write $( "div.bar" ).foo( "div.bar", {dog: "bark"} ); with the "div.bar" selector repeated as the first argument of .foo().

like image 33
b_levitt Avatar answered Sep 22 '22 06:09

b_levitt


As an extension to what Karim has put:

var t = jQuery('.clName');

t.each(function(){ 
   jQuery(this).data('selector',t.selector);
});
like image 36
vol7ron Avatar answered Sep 25 '22 06:09

vol7ron