Best Practice: Access form elements by HTML id or name attribute?

seth picture seth · Mar 12, 2010 · Viewed 210.7k times · Source

As any seasoned JavaScript developer knows, there are many (too many) ways to do the same thing. For example, say you have a text field as follows:

<form name="myForm">  
    <input type="text" name="foo" id="foo" />

There are many way to access this in JavaScript:

[1]  document.forms[0].elements[0];
[2]  document.myForm.foo;
[3]  document.getElementById('foo');
[4]  document.getElementById('myForm').foo;
     ... and so on ...

Methods [1] and [3] are well documented in the Mozilla Gecko documentation, but neither are ideal. [1] is just too general to be useful and [3] requires both an id and a name (assuming you will be posting the data to a server side language). Ideally, it would be best to have only an id attribute or a name attribute (having both is somewhat redundant, especially if the id isn't necessary for any css, and increases the likelihood of typos, etc).

[2] seems to be the most intuitive and it seems to be widely used, but I haven't seen it referenced in the Gecko documentation and I'm worried about both forwards compatibility and cross browser compatiblity (and of course I want to be as standards compliant as possible).

So what's best practice here? Can anyone point to something in the DOM documentation or W3C specification that could resolve this?

Note I am specifically interested in a non-library solution (jQuery/Prototype).

Answer

Doin picture Doin · Feb 11, 2014

Give your form an id only, and your input a name only:

<form id="myform">
  <input type="text" name="foo">

Then the most standards-compliant and least problematic way to access your input element is via:

document.getElementById("myform").elements["foo"]

using .elements["foo"] instead of just .foo is preferable because the latter might return a property of the form named "foo" rather than a HTML element!