Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax from jQuery to vanilla JavaScript. Function does not work the same [duplicate]

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!

like image 878
fullstackwannabe Avatar asked Jul 04 '26 09:07

fullstackwannabe


1 Answers

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);
});
like image 134
Tân Avatar answered Jul 06 '26 23:07

Tân



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!