VIDesignz
VIDesignz

Reputation: 4783

How can I retrieve the target element that a jquery plugin is attached to?

I am new to writing JQuery Plugins...and have a question regarding returning the selector used to bind the plugin to.

Lets say we attach a jQuery plugin to an element like this...

 $(".someClass").viEdit();

And this is the Plugin ...

(function ($) {
    $.fn.viEdit = function () {

        var myTarget = "????"; // See Below

    };
}(jQuery));

Now...How can I retrieve the target that was used to bind the jQuery?

I don't mean $(this), I'm looking for .someClass in this case.

As a second example, if it was set like this...

 $("#myElement").viEdit();

I would be looking for...

 #myElement

Any help would be greatly appreciated!

Upvotes: 0

Views: 497

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

There were a .selector property, which is deprecated in newer versions.

The advised method now is to pass it as a option like

(function ($) {
    $.fn.viEdit = function (options) {

        var myTarget = options.target;

    };
}(jQuery));

$("#myElement").viEdit({
    target: '#myElement'
});

Upvotes: 1

Jason P
Jason P

Reputation: 27012

You can use this.selector:

http://jsfiddle.net/3NAwD/

(function ($) {
    $.fn.viEdit = function () {

        console.log(this.selector);

    };
}(jQuery));

Note that something like $(document.getElementById('someId')).viEdit(); will give you a blank selector.

Upvotes: 1

Related Questions