0

I was looking at some sample code tutorials and noticed that on Javascript-coder.com, the author has several entries about form access which use two different methods of accessing form elements without explanation.

Example:

var myForm = document.forms["myForm"];
var elem = myForm[anInputName];
//OR
var myForm = document.forms["myForm"];
var elem = myForm.elements[anInputName];

Both appear to provide valid access to the element. Google just seems to crap out a bunch of syntax references. Why do both work?

1 Answer 1

1

Javascript forms have the elements collection which is an array of all form elements, but JS will also allow you to access the form elements by object key, as in your first example above.

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

3 Comments

Is there any reason to go with one or the other, or is it personal style?
Completely down to personal choice, both are equally valid and point to the same objects. Personally I'd pick the 1st method as it's a tiny bit less to code.
The "elements" array property provides the ability to easily loop through elements of a form, looping through object properties in javascript can be a bit more complicated.

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.