tags:

views:

57

answers:

3
<form name='form1'>
   <select name='sel1'></select>
</form>

<script>
   document.form1.sel1 ...  //access element by it's name attribute, is this standard?
</script>
+5  A: 

The right syntax is :

document.forms.form1.elements.sel1

or

document.forms["form1"].elements["sel1"]
Fabien Ménager
ok. thanks ......
lovespring
A: 

Why not do document.getElementsByName('sel1')?

There might be other elements with that name in the same document (e.g. multiple forms containing similar sets of controls) – David Dorward 31 mins ago

Thats why I always use id instead of name. I'd recommend using either the forms array or assigning an id to the element for easier retrieval.

voyager
There might be other elements with that name in the same document (e.g. multiple forms containing similar sets of controls)
David Dorward
Point taken ` ` ` ` ` `
voyager
thanks.........
lovespring
If you work off name, then you can reuse the JS between different forms, and just switch in a different form object. :)
David Dorward
+4  A: 

No, it is not specified in DOM Level 2 HTML that an HTMLDocument will gain named forms as direct properties, nor that HTMLFormElement will gain named elements as direct properties.

However the behaviour does stretch back to the very earliest implementation of JavaScript (in Netscape 2) and has been copied by every browser since, so it's one of those “DOM Level 0” features that though not formally recognised by any standards body is certainly a de facto standard.

I still wouldn't recommend using it, because future browsers may introduce new properties on HTMLDocument and HTMLFormElement (as browsers have regularly done in the past especially on HTMLDocument) whose names may clash with your name attributes. This is much, much less likely to happen on the HTMLCollection object used by the document.forms and form.elements properties.

Better still is to put id on anything you want to reference, leave the name off <form> and use the unambiguous document.getElementById().

bobince