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.
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.
You are confusing getElementsByTagName with getElementsByName. TagName is picking up <form> but Name is <form name='XYZ'>.
Couldn't you use
var f = document.getElementByID('some_id');
alert(f.value);
精彩评论