Form elements of the same name reflected in the DOM

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.

+6
source share
2 answers

It covers the draft HTML5 specification (and the WHAT-WG version), which in this case is more reminiscent of the documentation of how it always works in the HTMLFormControlsCollection ( W3C ref , WHAT-WG ref ) section:

If there are several matching elements, then [ HTMLFormControlsCollection ( W3C ref , WHAT-WG ref ) containing all of these elements.

+2
source

There seems to be a difference between form 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 
0
source

Source: https://habr.com/ru/post/891532/


All Articles