1

I added a button to my HTML and want to access the properties of it such as class, id or other attributes.

If I add an EventListener of click to the button using the ES6 arrow function and try to access its className with "this.className". The console logs in saying 'undefined !'

On the other hand, if I dont use arrow function but declare like "function(){ }" inside the EventListener I can access the className using 'this' keyword.

Can I know why is this happening ?

Here is my HTML code

<body>
   <button class="custom_btn btn btn-primary" >Click Me !</button>
</body>

My Javascript Code

//Cannot access className using this keyword inside an arrow function
//the console prints 'undefined'

document.querySelector('.btn-primary').addEventListener('click', () => {
  console.log(this.className)
})
  • https://stackoverflow.com/questions/28798330/arrow-functions-and-this Already answered here – Esteban MANSART Nov 06 '20 at 10:46
  • Treating `this` differently is the **point** of arrow functions. – Quentin Nov 06 '20 at 10:47
  • If you prefer to use arrow functions in an `EventListener`, you can replace: `function(){console.log(this.className);}` with: `(e) => {console.log(e.target.className);}` – Rounin Nov 06 '20 at 10:56

0 Answers0