Difference in referring this variable in jquery

36 views Asked by At

I am confused between this variable in the below code.

jQuery.fn.extend({
   check: function() {
     return this.each(function() {
       this.checked = true;
     });
   },
   uncheck: function() {
      return this.each(function() {
        this.checked = false;
      });
   } 
});

// Use the newly created .check() method
$( "input[type='checkbox']" ).check();

Please tell me which this refers to which object.

1

There are 1 answers

4
Rory McCrossan On BEST ANSWER

In this.each, this refers to the collection of elements in the provided jQuery object. In your example, it would be all of the input[type="checkbox"] elements.

In this.checked, this is the single DOMElement within the iteration of the each loop.