1

Why some HTML elements are available as javascript global variables and other elements are not?

Why an input element is visible as global variable only if it is outside of a form?

With this simple page:

<html>
  <body>
    <form id="form1">
      <input id='input1' />
      <div id='div1'></div>
    </form>
  </body>
</html>

I have both div1 and input1 as global variables in Chrome, but in IE10 I input1 is undefined: http://jsfiddle.net/M5ExX/

If I remove the form and leave the div and the input, then both are defined, both in Chrome and in IE: http://jsfiddle.net/M5ExX/1

c69
  • 19,951
  • 7
  • 52
  • 82
stenci
  • 8,290
  • 14
  • 64
  • 104
  • HTML element IDs and global variables in JS are very different things. I'm having trouble figuring out what you're asking here. – Jeremy Gallant Jun 26 '13 at 16:19
  • 1
    I load the page, then I type `input1` or `div1` in the javascript console of the browser. The javascript global variables are automatically created using the element IDs. – stenci Jun 26 '13 at 16:22
  • 3
    Ahh, ok. In that case, the behavior is discussed [here](http://stackoverflow.com/a/3434388/1655495) – Jeremy Gallant Jun 26 '13 at 16:25
  • 1
    Thanks, it's clearer now, even if it doesn't answer the question why that `input1` becomes a global variable when outside a form and not when inside. Chrome is consistent, but IE (which started this!) only creates the global when it likes. – stenci Jun 26 '13 at 16:31

0 Answers0