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 ) {
if(typeof selector === 'string') {
return jQuery.fn._init(selector, context).data('selector', selector);
}
return 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'