5

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?

1 Answers1

4

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.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130