It's nothing to do with the event handler; it's what's known as "named access on the window object":
HTML Standard[
^]
Basically, any element with an
id
or
name
becomes a property of the
window
object, making it a global variable.
Named Element IDs Can Be Referenced as JavaScript Globals | CSS-Tricks - CSS-Tricks[
^]
NB: Pay attention to the warning from the specification:
relying on this will lead to brittle code. Specifically, if your element ID is later introduced as a built-in API, your code will suddenly break for no obvious reason. It's far better to use
document.getElementById
to access the elements:
const btn1 = document.getElementById("btn1");
btn1.addEventListener("click", function(){
btn1.style.color = "red";
});
Alternatively, use the event object's
target
property to identify the element which triggered the event:
document.getElementById("btn1").addEventListener("click", function(e){
const btn = e.target;
btn.style.color = "red";
});