Joseph Khella Joseph Khella - 4 months ago 7
jQuery Question

Get the element calling a function in JQuery?

I have two JQuery elements like

$("myDiv1")
and
$("myDiv2")
and I defined a proto for it called
SetText()
,,
In
SetText
Implementation, How can I know that
myDiv1
is the one who called it if I did
$("myDiv1").SetText()
?
Thank you,

Answer

You use this:

  • Within your plugin code, it will refer to the jQuery object your plugin was called on
  • Within event handlers and such, it refers to the DOM element

Quick example:

// Our "nifty" plugin
(function($) {
  // Some default options
  var niftyDefaults = {
    color: "green"
  };
  $.fn.nifty = function(options) {
    // Get the options to use
    options = $.extend({}, niftyDefaults, options);
    
    // Here, `this` is a jQuery object; usually
    // you loop through it:
    this.each(function() {
      // Let's have our "nifty" set up an event handler
      // Note that here, `this` is the DOM element
      // for this iteration of the `each` loop
      $(this).on("click", function() {
        // And respond to it by setting the color
        // Here, `this` is the DOM element
        $(this).css("color", options.color);
      });
    });
  };
})(jQuery);

// Using it
$(".foo").nifty({color: "blue"});
$(".bar").nifty(/*defaults to green*/);
<div class="foo">foo</div>
<div class="bar">bar</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments