3

I have the following code in jQuery:

$("#input").change(function(){
    var input = this;
    console.log(input);
});

When there is a change in the input, the element is displayed in the console as html. I have tried to change this into plain JavaScript like this:

var img = document.getElementById('input');
img.addEventListener( 'change' , () => {
    var input = this;
    console.log(input);
});

The output in the console here is the whole html document, not only the input element. Can someone explain to me why this is happening?

Thank you!

2 Answers2

3

From the docs

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

So, everything you need to do in this case:

var img = document.getElementById('input');
img.addEventListener( 'change' , function () {
    var input = this;
    console.log(input);
});
Tân
  • 1
  • 15
  • 56
  • 102
  • 1
    Alright! Thanks! I totally forgot about that and changed my code to adding an event parameter in the function and storing event.target in my input variable which I found out returns the targeted input. Thank you for clearing things out for me! – fullstackwannabe Jan 17 '20 at 15:03
  • 1
    Alternatively you can keep the arrow function and access the element which raised the event from the argument passed to the handler function. – Rory McCrossan Jan 17 '20 at 15:05
1

It happens because arrow functions don't create a new scope. Change the arrow function in your second example to

img.addEventListener('change', function () {
    var input = this;
    console.log(input);
});

and it'll work exactly like your first example.

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

David
  • 3,552
  • 1
  • 13
  • 24