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.

4
  • 1
    Just read the W3C DOM 2 HTML spec regarding document.forms, which is an HTMLCollection whose the members can be referenced by index, id or name. Commented Jul 7, 2011 at 1: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 <a>?? Commented Jul 7, 2011 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. Commented Jul 8, 2011 at 5:39
  • This isn't a duplicate....keep closing posts which are SIMILAR. Commented Aug 9, 2012 at 22:12

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments