An HTML Element Presented in JavaScript as a Global Variable How How?

Does JavaScript designate each HTML element as a global variable whose name is the identifier 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 a new issue in JavaScript?
  • Is it better to get the element by id?
  • Why do they implement this functionality, although using global variables is not best practice?
+5
source share
1 answer

This is called named access . Each element having an id will be referenced in the global scope. This is a window object . Although not recommended, it is standardized using HTML5 .

A simple conflicting case for using it is

If you declare a variable in the global scope, for example hide , and also you have element in document with id hide . Then this element reference will be overridden by our global variable . At that time, if you use it ( element reference) in any event handler or somewhere, this will lead to an error.

+4
source

Source: https://habr.com/ru/post/1244720/


All Articles