30

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?

Keavon
  • 6,837
  • 9
  • 51
  • 79
Richard Testani
  • 1,474
  • 4
  • 15
  • 29
  • 1
    duplicate of http://stackoverflow.com/questions/500246/how-do-i-get-a-jquery-selectors-expression-as-text – jbabey Feb 21 '12 at 17:22

8 Answers8

40

You can use selector property:

$('my_selector p').selector // my_selector p

version deprecated: 1.7, removed: 1.9

AlbertoFdzM
  • 1,023
  • 11
  • 24
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 10
    This is deprecated since jQuery 1.7 – look tibc-dev answer. – skz Jun 23 '14 at 12:58
  • @skz is right the jQuery property selector was **deprecated since 1.7** and **removed on 1.9**: [jQuery .selector property (Removed, Deprecated)](https://api.jquery.com/selector/) – AlbertoFdzM Apr 08 '15 at 09:00
  • 29
    Instead of stating it is deprecated and removed, how about you tell us the appropriate alternative. – Studocwho Sep 11 '17 at 20:31
15

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.

tibc-dev
  • 973
  • 11
  • 16
  • 3
    what if $(this).attr('class') returns more than a single class? this would make an invalid selector, you should do '.'+$(this).attr('class').split(" ").join(".") instead. – vasilevich Dec 04 '16 at 01:08
  • Also if the selector is something like `.unique-class-123 p strong.help` it would only return `.help` – CodeBrauer Oct 27 '17 at 16:21
  • Correct code would be `(typeof($(this).attr('id')) !== 'undefined' && $(this).attr('id') !== null)` such as if selector is "undefined" but "not null" and ID is empty it will return `#undefined` – Yura Kosyak Nov 17 '21 at 14:02
2

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.

kevinmicke
  • 5,038
  • 2
  • 20
  • 22
1

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
Flinsch
  • 4,296
  • 1
  • 20
  • 29
bobbdelsol
  • 996
  • 6
  • 21
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
1
jQuery.fn.getSelector = function() {
        return this.data('selector');
};
yckart
  • 32,460
  • 9
  • 122
  • 129
wtrevino
  • 4,831
  • 2
  • 15
  • 9
0

Extending to kevinmicke's answer : You can get the selector in your event object that you pass on callback functions.

In callback functions

event.handleObj.selector

Example:

You'll get the selector string in e.handleObj.selector

    $( '.container' )
    .on('change', 'select.mySelector', function (e) {
        console.log(JSON.stringify(e));
        $('.selector').text(e.handleObj.selector);
        $('.value').text($(this).val());
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <select class="mySelector">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <h3>Your Selector: <span class="selector"></span></h3>
  <h3>Selected Value: <span class="value"></span></h3>
  
</div>

Console Log gives an object like this:

{
    // ...skipped lines
    "handleObj": {
        "type": "change",
        "origType": "change",
        "guid": 1,
        "selector": "select.mySelector",
        "needsContext": false,
        "namespace": ""
    }
}
Community
  • 1
  • 1
Imtiaz
  • 2,484
  • 2
  • 26
  • 32
0

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

Abdulhameed
  • 322
  • 3
  • 13