0

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.

1
  • 2
    Perhaps you'd get better explanation if you remove the getElementsByTagName function because people seem to think that's where your confusion lies. Just put in your example myform.foo or something and ask why foo works even when it's not a 'name'. Commented Jan 6, 2010 at 22:18

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

1 Comment

From my understanding, that's not his question. His question is why form.foo work when foo is an id, not name.
0

Couldn't you use

var f = document.getElementByID('some_id');
alert(f.value);

2 Comments

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').
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.