If you have multiple form elements with the same name
in a form, the entry in the elements
collection on the form ends up being a collection of those fields (which is handy). The DOM2 HTML specification covers the elements
collection but doesn't immediately seem to specify this behavior when there are multiple fields with the same name. Is the behavior covered by a standard (somewhere else in the DOM2 HTML specification, or in another spec)?
For clarity, I'm not asking what the best way to access these fields is. I'm asking whether the fact they end up in a collection (of varying kinds) on the elements
collection is covered by a standard, 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("L开发者_JAVA百科ooks 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've checked IE6, 7, 8, and 9, Firefox 4.0, Firefox 3.6, Chrome 12, Opera 11, and Safari 5. They all make the entry in elements
a collection of some kind (Chrome, Firefox, and Safari make it a NodeList
[though bizarrely on Safari the typeof
is "function" not "object"], and IE and Opera make it an HTMLCollection
, but they all have length
, item
, and []
access). I'm just trying to find the standard, if any, that specifies the behavior.
It's covered by the draft HTML5 spec (and the WHAT-WG version), which in this case seems more about documenting how it’s always worked, under the section on HTMLFormControlsCollection
(W3C ref, WHAT-WG ref):
If there are multiple matching items, then a [
HTMLFormControlsCollection
(W3C ref, WHAT-WG ref) object containing all those elements is returned.
Seems there is a difference between forms access and DOM access in Firefox 4.0.1 and 5
http://jsfiddle.net/mplungjan/jMnWP/
form.foo:
typeof formFoo = object
Object#toString says: [object NodeList]
Looks like a collection of some kind:
0: one
1: two
document.getElementsByName("foo"):
typeof docFoo = object
Object#toString says: [object HTMLCollection]
Looks like a collection of some kind:
0: one
1: two
精彩评论