views:

85

answers:

3

This came as a surprise to me but I have a simple form with 3 fields in it. The fields dont have a "name" attribute to it. They instead have an "id" attribute.

However. I can still do a

var f = document.getElementsByTagName('form')[0];
alert(f.elementID);

to access the element. I thought to access form elements in that way, the "name" attribute is necessary.

I couldn't find any explanation somewhere for such a behavior. Any pointers ?

EDIT:

I think there is some confusion regarding my question.

my form fields dont have a "name" attribute. They have an "id". Still, I can do this :

myform.elementId

to access them.The question has nothing to do with getElementsByTagName.

+4  A: 

getElementsByTagName returns all elements of the given tag. (In your case, all <form> elements)

It doesn't return all element that have a name attribute, as you seem to be understanding it.

In your case, you could call getElementById to return the (single) element that has the given ID.


EDIT: I think I'm misunderstanding your question.

If you're asking why you can still write myform.elementId, that does use the element's ID.

SLaks
@sLaks doesnt that work with the element name ? maybe it works both with myform.elementName and myform.elementId
Rajat
+4  A: 

You are confusing getElementsByTagName with getElementsByName. TagName is picking up <form> but Name is <form name='XYZ'>.

Michael Bray
From my understanding, that's not his question. His question is why `form.foo` work when `foo` is an id, not name.
slebetman
@slebetman you are right. that is exactly what I mean.
Rajat
A: 

Couldn't you use

var f = document.getElementByID('some_id');
alert(f.value);
gnarf
No, since it is Id not ID and form elements do not have a value property (unless they contain a form control that is named 'value').
David Dorward
The OP States: The fields dont have a "name" attribute to it. They instead have an "id" attribute. --- This makes me assume he was looking to get to the form elements based on their ID.
gnarf