Re: Obtaining same named elements from the HTMLFormElement.elements collection

Boris Zbarsky <[email protected]> Wed, 14 Jul 2010 01:02:14 -0400
Newsgroups gmane.comp.mozilla.devel.dom
Message-ID <[email protected]>
On 7/13/10 12:22 PM, Stanimir Stamenkov wrote:
> I have a form in HTML document containing the following elements:
>
> <input type="checkbox" name="stuff" value="1">
> <input type="checkbox" name="stuff" value="2">
> <input type="checkbox" name="stuff" value="3">
>
> If 'form' is reference to the form, trying:
>
> window.alert(form.elements.namedItem('stuff'));
>
> yields "[object HTMLInputElement]", while using:
>
> window.alert(form.elements['stuff']);
>
> yields "[object NodeList]". Using Safari 5/Chrome 5 both forms yield
> "[object NodeList]". Using Opera 10.60/IE8 both forms yield "[object
> HTMLCollection]". Which one is right?

It depends on which spec you read.

In DOM Level 2 HTML [1], form.elements is defined as an HTMLCollection; 
the namedItem method on HTMLCollection, as defined in the same 
specification, returns a Node.  Hence the Gecko behavior.

The behavior of elements['stuff'] is defined in the ECMAScript bindings 
for Dom Level 2 HTML [2] to do the same thing as namedItem.  However 
that's never been web-compatible, since no browser has ever implemented 
that behavior.  The actual behavior browsers had is not defined anywhere 
in the DOM Level 2 specs.

In the current HTML5 draft [3], form.elements is an 
HTMLFormControlsCollection, and has both ['stuff'] and namedItem defined 
to return either a list or node depending on how many items with that 
name are in the collection.  That is, the draft alignes with the 
Webkit/Opera/IE behavior in terms of what sort of behavior the returned 
object should have; as you will note none of the above toString 
behaviors are correct per the current HTML5 draft.  The correct thing 
would be "[object HTMLFormControlsCollection]" I would think.

> I've given HTMLCollection.namedItem(name) a try as accessing form
> elements with name of "item" like |form.elements['item']| gives me the
> function item() of the HTMLCollection, instead of the needed elements.
> This however brought the above discrepancy and I'm not sure I can safely
> use cross-browser |form.elements['field-name']| to obtain a collection
> with all form elements with name of "field-name", anymore.

I can't find the exact part of HTML5/WebIDL that would tell me what 
should happen for ['item'] here.  I'm sure it's either out there or will 
be sometime...

In any case, it's worth filing a bug on us to change our namedItem behavior.

-Boris

[1] http://www.w3.org/TR/DOM-Level-2-HTML/html.html
[2] http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
[3] http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html