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!
From the docs
An arrow function does not have its own
this. Thethisvalue of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching forthiswhich is not present in current scope, an arrow function ends up finding thethisfrom 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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With