views:

119

answers:

4

I've found that given a form in a HTML page like this:

<form name="form">
   <input type="image" name="foo" 
          src="somewhere.gif" alt="image" value="blah"/>
   <input type="text" name="bar" value="blah"/>
</form>

When accessing the elements via the DOM in Javascript, there is no element for the image input! It is just omitted. So, document.forms[0].elements.length is 1, and document.forms[0].element[0].type is "text".

This seems to be the case in Firefox, and IE. I can't find this fact documented anywhere in my reference books or on the web. All I can find is a throwaway comment here:

https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4

Which suggests it "just is like this". If so, well so be it - but is it really not documented anywhere? Is it a historical mistake, or is there a reason for it?

+1  A: 

It looks like that's the behavior of the elements property in all browsers.

However, you should still be able to access it through the DOM in JavaScript using the childNodes property.

For your example:

document.forms[0].childNodes.length; // equals 5 (2 inputs and 3 text nodes).
document.forms[0].childNodes[1];     // This is your input with type='image'
Adam Bellaire
A: 

Interesting... the DOM 1 spec defines .elements as:

elements Returns a collection of all control elements in the form.

The HTML 4 spec part 17.2.1 doesn't list "image" types, so I guess that's the answer.

Greg
True, but then it doesn't list the `textarea`, or `select` "inputs", and they *do* appear in the `.element` property
The HTML spec you link to _does_ list image types (between submit and reset), unless I don't understand what you said.
PhiLho
A: 

Indeed, I see a comment: "The DOM is supposed to work that way, that's how it works in Mozilla, NS4x, and IE. We can't change that even if we wanted to, lots of sites would break." so I would lean toward an historical error. Image element is already in HTML 2 DTD...

Perhaps that's for that and possible other culprits that authors discourage using Dom hierarchy like that in favor of getElement[s]ByXxx functions (or XPath!).

PhiLho
A: 

Been bitten by it myself. It's stated in the MSDN DHTML docs.

David Grant