0

Why is $(this) returning undefined instead of the clicked element?

I've replaced $(this) with event.target and it works fine but would like to understand the issue with $(this), thank you!

$('.nav-search-options').on('click', (event) => {

  console.log($(this))

})

1 Answers1

2

@JamesJavascript. It is partially right what Justinas said in the comment about arrow function - although there are more things to add.

Arrow functions do not have their own "this", instead they bind one from their parent scope.

To see what I mean, try this and see that it returns you the window object:

const myFunction = () => {
  console.log(this);
};

// call it
myFunction();

Read more about it here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Kateryna
  • 56
  • 6