-5

So, here is the question

I can not undestand when i should use "this" instead class or id

If u can show example - it will be fantastic

Thanks

Nikita Shchypylov
  • 347
  • 1
  • 3
  • 13

1 Answers1

1

I can not undestand when i should use "this" instead class or id

Usually, you do that when you want to refer to the element on which an event was triggered from within the event handler:

$(".foo").on("click", function() {
    var $el = $(this);           // `this` is the element that was clicked,
                                 // so `$(this)` gives you a jQuery wrapper
                                 // around just that one element.
                                 // But $(".foo") would give you a wrapper
                                 // around **all** .foo elements, not just the
                                 // one that was clicked.
    // ...
});

Live Example:

$(".foo").on("click", function() {
  var $el = $(this); // `this` is the element that was clicked
  $el.text("You've clicked this one");
});
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sometimes, it comes up when using either each or $.each, because jQuery calls the callback to each of those methods with this referring to the element for that call:

$(".foo").each(function() {
    var $el = $(this);               // `this` is the element for this callback
    // ...
});

The jQuery API documentation will tell you when it's going to set this to a specific value in a callback.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • but we can use var $el = $(.foo) too, right? – Nikita Shchypylov Mar 18 '16 at 12:42
  • @НикитаЩипилов: Only if you want `$el` to refer to **all** `.foo` elements, instead of the specific one that was clicked. – T.J. Crowder Mar 18 '16 at 12:42
  • @НикитаЩипилов T.J said it well, you just have to read carefully, Yes you can assign `$el = $(".myEl")`, but **within** a callback function (inside a jQuery's Method callback) you refer using `$(this)` to the element who registered (triggered) such bound event / Method. If your element is already assigned to `$el` noone stops you to use that variable instead. – Roko C. Buljan Mar 18 '16 at 12:44