How do I get a jQuery selector's expression as text?

There is a 'selector' attribute in the jQuery object, but I'm not sure it's always available.


This is far from optimal but works in some cases. You could do the following:

jQuery.fn._init = jQuery.fn.init
jQuery.fn.init = function( selector, context ) {
    return (typeof selector === 'string') ? jQuery.fn._init(selector, context).data('selector', selector) : jQuery.fn._init( selector, context );
};

jQuery.fn.getSelector = function() {
    return jQuery(this).data('selector');
};

This will return the last selector used for the element. But it will not work on non existing elements.

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $('#foo').getSelector(); //'#foo'
 $('div[id="foo"]').getSelector(); //'div[id="foo"]'
 $('#iDoNotExist').getSelector(); // undefined
</script>

This works with jQuery 1.2.6 and 1.3.1 and possibly other versions.

Also:

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $foo = $('div#foo');
 $('#foo').getSelector(); //'#foo'
 $foo.getSelector(); //'#foo' instead of 'div#foo'
</script>

Edit
If you check immidiatly after the selector has been used you could use the following in your plugin:

jQuery.getLastSelector = function() {
    return jQuery.getLastSelector.lastSelector;
};
jQuery.fn._init = jQuery.fn.init
jQuery.fn.init = function( selector, context ) {
    if(typeof selector === 'string') {
        jQuery.getLastSelector.lastSelector = selector;
    }
    return jQuery.fn._init( selector, context );
};

Then the following would work:

<div id='foo'>Select me!</div>
<script type='text/javascript'>
 $('div#foo');
 $.getLastSelector(); //'#foo'
 $('#iDoNotExist');
 $.getLastSelector(); // #iDoNotExist'
</script>

In your plugin you could do:

jQuery.fn.myPlugin = function(){
 selector = $.getLastSelector;
 alert(selector);
 this.each( function() {
  //do plugins stuff
 }
}

$('div').myPlugin(); //alerts 'div'
$('#iDoNotExist').myPlugin(); //alerts '#iDoNotExist'

But still:

$div = $('div');
$('foo');
$div.myPlugin(); //alerts 'foo'

If you're using firebug you could console.log(this) inside the function and see if the selector string is accessible somewhere in the object. Sorry I am not familiar with the jQuery API.