0

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

The forms on my site all have "id" attributes as follows...f0,f1,f2..., and this is how I access them. My understanding is that Javascript creates an aray that hold the forms and I can access them this was as well.

By id:

var a='f0';
var c=document.forms[a].elements;

By array index:

var c=document.forms[0].elements;

By name:

var a='f0';
var c=document.forms[a].elements;

Which way is better, I just picked by id as a starting point.

Community
  • 1
  • 1
  • 1
    Just read the W3C DOM 2 HTML spec regarding [document.forms](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-1689064), which is an [HTMLCollection](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506) whose the members can be referenced by *index*, *id* or *name*. – RobG Jul 07 '11 at 01:00
  • Thanks, this is pretty abstract - collections, nodes and what not I wish there was a Cliff Notes. A collection is a list of nodes. What is a node? An element like ?? –  Jul 07 '11 at 20:40
  • Yes. The DOM specs are language neutral. Elements are nodes, but not all nodes are elements (e.g. text nodes, attribute nodes, etc.). Some DOM interfaces return a NodeList, the HTML specs extend that for HTML documents to include HTMLCollections, which is a NodeList of HTML elements. – RobG Jul 08 '11 at 05:39
  • This isn't a duplicate....keep closing posts which are SIMILAR. –  Aug 09 '12 at 22:12

3 Answers3

1

ID and Name are 2 different things:

var a='f0';
var c=document.forms[0].elements[a];

is accessing the element by name

example

<input name="f0" value="value" />

accessing by id is doene this way

var a='f0';
var c=document.getElementById(a);
Ibu
  • 42,752
  • 13
  • 76
  • 103
0

If I have more than one on the page I use the id, there is less room for confusion and its more expressive and intuitive for any developers that are in the code after you.

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
0

Stick with what you've got - ID is more explicit. Index is nearly arbitrary and will cause headaches if the code is ever changed.

gilly3
  • 87,962
  • 25
  • 144
  • 176