5

Discovered this weird behavior today. If I had the following HTML:

<form>
  <h1 id="test">Test</h1>
</form>

Why does this JS work:

console.log(test); // This outputs the <h1> element. 
                   // Why does this work? Shouldn't `test` be undefined?

I haven't declared test anywhere else. This behavior only seems to happen for elements that are inside a <form>.

Saad
  • 49,729
  • 21
  • 73
  • 112
  • 2
    The browser may define the variable for you. [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) Also note [Is there a spec that the id of elements should be made global variable?](http://stackoverflow.com/questions/6381425/is-there-a-spec-that-the-id-of-elements-should-be-made-global-variable) – Jonathan Lonowski Nov 22 '15 at 03:16
  • Also related: [JavaScript variable corresponds to DOM element with the same ID](http://stackoverflow.com/questions/5515659/javascript-variable-corresponds-to-dom-element-with-the-same-id) – Josh Crozier Nov 22 '15 at 03:17
  • *"This behavior only seems to happen for elements that are inside a `
    `."* [Nope](http://jsfiddle.net/wbL3yr9q/).
    – Felix Kling Nov 22 '15 at 03:36
  • @FelixKling Yeah, you're right. I think the only reason I assumed that was because I had my own var of the same name for a different element when I was testing this out before. Thanks. – Saad Nov 22 '15 at 03:39

0 Answers0