8

Previous to using ES6 arrow functions, if I wanted to get the element from a jQuery on() click event then I could do something like this:

$(document).on('click', '.inserted-el', function(event) {
    console.log(this);
});

However, with the arrow function, I can no longer access this in that way. How do I get hold of the element that was clicked on?

a better oliver
  • 26,330
  • 2
  • 58
  • 66
Fisu
  • 3,294
  • 9
  • 39
  • 61

2 Answers2

10

You can use event.currentTarget to refer to the target element of the handler

$(document).on('click', '.inserted-el', function(event) {
  snippet.log('old -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
$(document).on('click', '.inserted-el', (event) => {
  snippet.log('new -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="inserted-el">1</button>
<button class="inserted-el">2</button>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2
`event.currentTarget` 

is your friend here.

The reason you can't access it as 'this' is because arrow functions have the same 'this' as their parent scope.

You should also know about event.target

http://joequery.me/code/event-target-vs-event-currenttarget-30-seconds/

Tom
  • 7,994
  • 8
  • 45
  • 62