I wish I could write something like this
$("div.banana .for aside.scale").yellowify();
$.fn.yellowify = function () {
this.css("color","yellow");
alert($(this).selector);
});
which would alert
div.banana .for aside.scale
The question is very similar to this one, however, there the poster wants to retrieve a DOM structure by scanning parents of the selector or something like that. I simply want the selector as is, without any additional classes or IDs. I want it exactly as it's there in the first line.
jQuery used to have this .selector
property, but it has been deprecated in 1.7 and removed in 1.9 (or has it? - thanks Ted. UPDATE .selector
will only be removed in jQuery 3.0!). The docs state:
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"} ); with the "div.bar" selector repeated as the first argument of .foo().
But I think that that's incredibly ugly and not user-friendly at all. Is there an alternative possible that doesn't require any action on the user's side? I.e. without needing any additional arguments?
For those who are curious, ideally I want my plugin to be able to echo styles for the specific element, something like this, but obviously much more complicated:
$.fn.yellowify = function () {
var css = $(this).selector + "{color: yellow;}";
// I can add rules for specific elements now as well
css += $(this).selector + " .child {color: red;}";
$("<style>").html(css).appendTo("head");
});
Together with arguments, this allows me to have a far reach with my plugin.