Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Why does using "this" on an checkbox event listener not return the dom object, but rather the window object?

I have an event listener on a checkbox that passes a few arguments using "this", however for some reason it doesn't work.

Upon sending "this" to the console, I can see that unlike my other event listeners that I'm using for text input and select nodes, that it's returning the entire window object

The code I'm using:

document.getElementById("nightMode").addEventListener('change', () => {
    console.log(this)
})

What I would expect to see in console:

<input id="nightMode" type="checkbox" />

What is actually being sent to the console:

Window {window: Window, self: Window, document: document, name: '', location: Location, …}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It's because you're using an arrow function ( () => { ... } ). Replace it with a normal function ( function() { ... } ).

Arrow functions don't have a this of their own. It cannot change; this inside an arrow function will always point to whatever this was at the point in time when the function was declared.

about 4 years ago · Juan Pablo Isaza Report

0

use this code instead:

<input id="nightMode" type="checkbox" onchange="alert(this)">
about 4 years ago · Juan Pablo Isaza Report

0

That's because when you use arrow function, you have binded this of your global scope ( Window ) to your handler function.

Try to use normal function decalration instead: function () { ... }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!