0

Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?

Description:

Hi there I just noticed that when I use an id on a form it's available as a global variable after this. I tested this on Firefox 17.0 and Google Chrome 23.0 both on a Mac. I was kinda surprised when I saw this!

HTML-Code:

<form class="input-form" id="test">
      <label for="key">Key</label>
      <input type="text" name="key">
</form>

Question:

Does this mean it's actually a very bad idea to use id's on a from or am I completely wrong?

Thanks in advance.

Community
  • 1
  • 1
Playerwtf
  • 301
  • 1
  • 4
  • 12
  • 2
    I believe this happens for any element that you give an ID - there's nothing you can do to avoid it, just make sure you're not *using* that global variable to reference the element - that's what `getElementById` is for. [Related question](http://stackoverflow.com/questions/6381425/should-the-id-of-elements-be-made-global-variables-and). – jbabey Dec 03 '12 at 13:32
  • 1
    Here is an answer: [are DOM tree elements global variables here?](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – Michael Malinovskij Dec 03 '12 at 13:38
  • Thanks for both answers very useful. Thats why I like stackoverflow! – Playerwtf Dec 03 '12 at 15:29

2 Answers2

1

If you mean that it's available in browsers console than it's ok. It's just a way browser trying to ease the pain of writing document.getElementById('test'). At least it's the case with Chrome. If you open the Chrome console (for example on this page) and just type "sidebar" and hit enter, you'll see that it returns div with id "sidebar".

To answer directly to your question: it's completely normal to use an id on a form (or any other node) for that matter.

WTK
  • 16,583
  • 6
  • 35
  • 45
0

Its normal if your form is a direct child in body. For example:

<body>
<form id="myForm" >
    <input type="file"/>
    <div>
        <form id="myForm2" >
            <input type="text" />
        </form>
    </div>
</form>
</body>

myForm will be available as a global varialble. But myForm2 will not be available.

Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57