0

I'm having an issue with jQuery where when selecting an element with nth-of-type() within the bound function, it will not allow me to access it with $(this)

$(".panel:nth-of-type(2)").on('click', (e) => {
  alert("CLICKED PANEL 2");
  $(this).css({
    background: "red"
  });
});

The above will run the alert() but the $(this) does not get hit and throws no errors. If I change the $(this) to $(".panel:nth-of-type(2)") it will then work without any issues.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • `$(".panel:nth-of-type(2)", this)` is the same as `$(this).find(".panel:nth-of-type(2)")`, so it all depends on what `this` refers to when that code runs. – Pointy Jul 20 '19 at 18:31
  • @Pointy My bad, that is not what I'm actually trying to run... updated the question. – Joe Scotto Jul 20 '19 at 18:31
  • Have you done a `console.log(this)` to see what its value is? jQuery will *definitely* set it to some element when it invokes the handler. *edit* — well it'll try at least :) – Pointy Jul 20 '19 at 18:32

2 Answers2

2

You're using an arrow function. These have no access to this. Arrow functions use lexical scoping.

You have 2 options. Either convert the function to a normal one, or use e.currentTarget instead of this

$(".panel:nth-of-type(2)").on('click', function (e) {
  alert("CLICKED PANEL 2");
  $(this).css({
    background: "red"
  });
});
.panel {
  border: 1px solid black;
  width: 100px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>

Using e.currentTarget

$(".panel:nth-of-type(2)").on('click', (e) => {
      alert("CLICKED PANEL 2");
      $(e.currentTarget).css({
        background: "red"
      });
    });
.panel {
 border: 1px solid black;
 width: 100px;
 height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
<div class="panel"></div>
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
1

I have got the similar situation, and it's better not to use the => fat arrow function for this, assuming it changes the context of this. Use a regular function:

$(".panel:nth-of-type(2)").on('click', function (e) {
  alert("CLICKED PANEL 2");
  $(this).css({
    background: "red"
  });
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252