E
E
elyourn2015-10-06 16:12:03
JavaScript
elyourn, 2015-10-06 16:12:03

Js: Why doesn't the interpreter return var is not defined when accessing id?

I was at an interview and asked this question. Code below. Please explain the logic of work.

<div id="test"></div>
<script>
console.log(test);
</script>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Ivan Solomennikov, 2015-10-06
@elyourn

If the id attribute is used to name an HTML element, and if the Window object does not already have a property whose name matches the value of the id attribute, then the Window object receives a non-enumerable property with a name corresponding to the value of the id attribute, whose value becomes the HTMLElement object that represents that document element. Thus, the values ​​of the id attribute in HTML documents become global variables available to scripts. If, for example, the document includes an element <button id="okay">, then it can be referenced using the "okay" global variable. © David Flanagan.

D
Dmitry Novikov, 2015-10-06
@dmitriy_novikov

Because the variable is not declared via var and matches the element's id.
In this case, document elements with id are available as global variables with the same names.
Old joke.

V
Vitaly Inchin ☢, 2015-10-06
@In4in


If an element has a special id attribute assigned, then you can get it directly by the variable with the name from the id value.
This behavior is in accordance with the standard. It exists primarily for compatibility, as a piece of the distant past and is not very welcome, because it uses global variables. The browser tries to help us by mixing JS and DOM namespaces, but conflicts are possible.

https://learn.javascript.ru/searching-elements-dom...

A
Alexander Zubarev, 2015-10-06
@zualex

Because test is a global variable in window. Here is a link to the html standard (the site takes a long time to open!).
Returns the indicated element or collection of elements.
But if you use this approach, it will lead to fragile code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question