If you have a form element within a form and that element has a name
or id
, you can access it directly off the form's DOM element as a property with that name. This behavior appears to be very broadly-supported. Is it covered by any specification, and if so, which one?
This behavior for a form's elements
collection is specified in the DOM2 HTML spec, but I'm not immediately seeing the business of dumping the elements as properties on the form itself specified anywhere, unless the phrase "It provides direct access to the contained form controls as well as the attributes of the form element." here is meant to say that (if so, wow is that subtle, I read it as referring to the elements
collection). I'm guessing it's just legacy behavior.
For clarity: I'm not asking what the best way to access form fields is, I'm asking if this behavior is covered by a standard. (I'm also avoiding the whole business of things being dumped on the window
object; that's a whole other topic.)
Example (live copy):
HTML:
<form id="theForm">
<input type="text" name="field1" value="foo">
<input type="text" id="field2" value="bar">
</form>
JavaScript:
var f = document.getElementById("theForm");
console.log(f.elements.field1.value); // "foo", per spec
console.log(f.field1.value); // also "foo"
console.log(f.elements.field2.value); // "bar", per spec
console.log(f.field2.value); // also "bar"
I've checked IE6, 7, 8, and 9, Firefox 4.0, Firefox 3.6, Chrome 12, Opera 11, and Safari 5. They all do it (make the form fields available in both places).