Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML element is represented in JavaScript as a global variable , How? [duplicate]

Does JavaScript represent each HTML element as a global variable which name is the id of the element ?

Let's say I have a hidden input element like this:

<input type="hidden" value="10" id="myInput" />

so I can access it in JavaScript :

console.log(myInput.value);

I tried it in chrome and firefox, and it worked for me.

My question is :

  • Is this issue new in JavaScript ?
  • Is it the best practice to get an element by id ?
  • Why they implement this functionality although using global variables is not the best practice?
like image 379
Mohamed ElHamamsy Avatar asked Sep 25 '22 03:09

Mohamed ElHamamsy


1 Answers

That is called as named access. Every element which has an id will be referenced in global scope. That is the window object. Even though it is not a good practice to use it, it is standardised with HTML5.

A simple conflicting case for its usage is,

If you declare a variable in global scope like hide, and also you are having an element in your document with id hide. Then that element reference will be overridden by our global variable. At that time, if you use it(element reference) in any event handler or somewhere, it will results in error.

like image 179
Rajaprabhu Aravindasamy Avatar answered Nov 15 '22 05:11

Rajaprabhu Aravindasamy