0
console.log($('.divs').click(<function>)) 

This shows an array of divs. Does the click method return the object it acts on? It is just something basic - maybe someone can say more. That $() returns the array of elements with that selector makes natural sense. But $(<selector>).click(<function definition>) - just defines what should happen on each element of $(<selector>) when it is clicked - why does it also "return" the array of elements?

Here is also a fiddle for the above http://jsfiddle.net/jy7kpL6f/

or here - HTML/CSS/jQuery

var addclass = 'color';
var $cols = $('.divs').click(function(e) {
  $cols.removeClass(addclass);
  $(this).addClass(addclass);
});
var $cols2 = $('.divs');

console.log($('.divs').click(function(e) {
  $cols.removeClass(addclass);
  $(this).addClass(addclass);
}));
.color {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="divs">
  1st Div
</div>
<div class="divs">
  2nd Div
</div>
<div class="divs">
  3rd Div
</div>
<div class="divs">
  4th Div
</div>
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 1
    `click()` returns a jQuery object which contains all the selected elements in order to enable method chaining. This is expected behaviour. It's only the event handler function which runs under the context of the single Element instance which triggered the event. – Rory McCrossan Jan 31 '19 at 10:45

2 Answers2

1

click() returns all selected elements like many other jQuery functions.

This can be handy to chain functions like this:

$(".divs")
    .click(callback1)
    .hover(callback2)

...etc

Niklas Hantke
  • 353
  • 1
  • 5
  • 20
1

Yes, it does. It returns the elements due to something called chaining. It enables such calls as:

$('div').addClass('on').removeClass('off');
markmoxx
  • 1,492
  • 1
  • 11
  • 21