Rusi Nova
Rusi Nova

Reputation: 2655

How to know the selector inside jquery plugin?

I have created a plugin like

jQuery.fn.Foo = function () { 

    //var str=   get selector some_how; alert(str);      

    //at this point get selector that invoked this function

    //eg:
    /*
         jQuery('.red').Foo(); // alerts .red
         jQuery('#something_else') // alerts  #something_else
    */


}

Upvotes: 0

Views: 447

Answers (2)

curveball
curveball

Reputation: 4505

That's how I get selector strings inside my plugins in 2017:

(function($, window, document, undefined) { 
    $.fn._init = $.fn.init
    $.fn.init = function( selector, context, root ) {
        return (typeof selector === 'string') ? new $.fn._init(selector, context, root).data('selector', selector) : new $.fn._init( selector, context, root );
    };
    $.fn.getSelector = function() {
        return $(this).data('selector');
    };
    $.fn.coolPlugin = function() {
        var selector = $(this).getSelector(); 
        if(selector) console.log(selector); // outputs p #boldText
    }
})(jQuery, window, document);

// calling plugin
$(document).ready(function() {
    $("p #boldText").coolPlugin();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>some <b id="boldText">bold text</b></p>

The idea is to conditionally wrap jQuery's init() function based on whether a selector string is provided or not. If it is provided, use jQuery's data() method to associate the selector string with the original init() which is called in the end. Small getSelector() plugin just takes previously stored value. It can be called later inside your plugin. It should work well with all jQuery versions.

Upvotes: 1

Dennis
Dennis

Reputation: 32598

jQuery objects have a selector attribute. You can access this.selector.

Upvotes: 2

Related Questions