Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HTML
<button id="btn1">Click me</button>


JavaScript
function fun(){
    btn1.style.color="red";
};
var mybtn1=document.getElementById("btn1");
mybtn1.addEventListener("click", fun);


What I have tried:

I don't understand how the function get access to direct an element from HTML without any parameter or specifying that element.
Posted
Updated 16-Jan-23 0:20am
Comments
Member 15627495 14-Jan-23 9:00am    
'mybtn1' is the tag "button".

in html page, you have the DOM and its elements.
the var mybtn1 contains the "button" element with the id "btn1"

It is all explained in the documentation: JavaScript DOM EventListener[^].
 
Share this answer
 
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:
JavaScript
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:
JavaScript
document.getElementById("btn1").addEventListener("click", function(e){
    const btn = e.target;
    btn.style.color = "red";
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900