<form name='form1'> <select name='sel1'></select> </form> <script> document.form1.sel1 ... //access element by it's name attribute, is this standard? </script>
views:
57answers:
3The right syntax is :
document.forms.form1.elements.sel1
or
document.forms["form1"].elements["sel1"]
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.
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()
.