If you have several form elements with the same name in the form, the entry in the elements collection in the form becomes a set of these fields (which is convenient). The HTML DOM2 specification covers the elements collection , but does not immediately indicate this behavior when there are multiple fields with the same name. Is the behavior standard (somewhere else in the HTML DOM2 specification or in another specification)?
For clarity, I am not asking what is the best way to access these fields. I ask if the fact that they fall into the collection (of different types) in the elements collection is elements , and if so, which one.
Example ( live copy ):
HTML:
<form id="theForm"> <input type="text" name="foo" value="one"> <input type="text" name="foo" value="two"> </form>
JavaScript:
var form = document.getElementById("theForm"), foo = form.elements.foo, index; console.log("typeof foo = " + typeof foo); if (typeof foo !== "undefined") { console.log("Object#toString says: " + Object.prototype.toString.call(foo)); } if ('length' in foo && 'item' in foo) { console.log("Looks like a collection of some kind:"); for (index = 0; index < foo.length; ++index) { console.log(index + ": " + foo[index].value); } }
Sample output (for Chrome):
typeof foo = object
Object # toString says: [object NodeList]
Looks like a collection of some kind:
0: one
1: two
I checked IE6, 7, 8, and 9, Firefox 4.0, Firefox 3.6, Chrome 12, Opera 11, and Safari 5. They all write a collection to elements (Chrome, Firefox, and Safari is a NodeList [although in Safari typeof it is a “function” not an “object”], and IE and Opera do this with an HTMLCollection , but they all have length , item , and [] access). I'm just trying to find a standard, if any, that defines behavior.