When calling a custom plugin, how can I get the current selector string?
$(\'my_selector p\').my_plugin();
Would like to output my_se
Being deprecated, the official advice is to add the selector as a parameter in your function call: https://api.jquery.com/selector/
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"} );
Redundant, yes, but it's always reliable.
Post selector deprecation v. 1.7:
If you're only dealing with ids and classes as selectors you can use the following:
var selector = (typeof($(this).attr('id')) !== 'undefined' || $(this).attr('id') !== null) ? '#' + $(this).attr('id') : '.' + $(this).attr('class');
There are cleaner ways but since the removal of .selector due to being inconsistent between browsers since 1.7, this has been my go-to.
With selector
deprecated i use
index = document.getElementById('category').value
select = $("#category option[value=#{index}]")[0].innerHTML
just two lines of code
or if you're really cheap with lines
select = $("#category option[value=#{document.getElementById('category').value}]")[0].innerHTML
Fully working with any jQuery version even after deprecation and removal of "selector" property
My solution is to intercept the selector at the time of jQuery object initialization and in the same time maintain all other jQuery functionalities transparently all this using inheritance as the following:
$ = (function (originalJQuery)
{
return (function ()
{
var newJQuery = originalJQuery.apply(this, arguments);
newJQuery.selector = arguments.length > 0 ? arguments[0] : null;
return newJQuery;
});
})($);
$.fn = $.prototype = jQuery.fn;
Usage:
var myAnchors = $('p > a');
var selector = myAnchors.selector;
Should produce: "p > a"
Tried it successfully with jQuery 3.4.1
Best workaroud is
function mySelector(selector) {
return $.extend($(selector),{"selector":selector});
}
this returns classic jquery object as $() would
mySelector(".myClass")
and this returns string of the selector
mySelector(".myClass").selector
jQuery.fn.getSelector = function() {
return this.data('selector');
};