Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'selector' return value differ from 'this'

Inside an event handler, why does $(this) return something else than $('.selector')?

Example:

$('.container').click(function () {
    console.log($(this));
    console.log($('.container'));
});

jsFiddle

When you look in the console the results are different.

like image 410
RobinvdA Avatar asked Dec 06 '22 01:12

RobinvdA


1 Answers

this is always the element on which the event originated, in other words which of the .container elements you clicked exactly.

e.g.:

<div class="container">container1</div>
<span class="container">container2</span>

as Jonathan Lonowski notes, $(".container") selects both .container elements but this is the one you clicked, either the span or the div.

Also, $(this) just wraps that element into a JQuery object, the this keyword itself is native javascript.

like image 108
MarioDS Avatar answered Dec 08 '22 16:12

MarioDS