When calling a custom plugin, how can I get the current selector string?
$('my_selector p').my_plugin();
Would like to output my_selector p
within my script. How can I access this string?
The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
The #id Selector The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector: $(document).
You can use selector
property:
$('my_selector p').selector // my_selector p
version deprecated: 1.7
, removed: 1.9
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.
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.
jQuery.fn.getSelector = function() {
return this.data('selector');
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With