Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There's some good stuff here, including stuff that I've learned over the years and some stuff I didn't yet know. But I don't quite understand this one:

> GOOD: document.forms["formname"].elements["inputname"]

> BAD: document.formname.inputname

Square bracket notation is awesome for mixing in variables - it saves you from using the evil eval() - and obviously BAD is worse than GOOD, but if you have no variables what about this:

> ?: document.forms.formname.inputname

If there's no functional difference it's shorter and simpler than GOOD



Neither is great practice, in my opinion. This page looks dated in its recommendations. Any sane JavaScript that works with DOM elements should use a DOM abstraction like jQuery. Leave document.forms.fooinput.parentNode.firstChild.nextSibling.godhelpme to die in the grave of DHTML and incompatible DOMs from the IE6 era.


I tend to use document.forms['foo'].elements['bar'], here's why:

I use the elements collection because the behaviour of adding each input as a property to the parent form element is a mistake.

I use the bracket notation because it highlights the difference between the implementation symbols and the actual data which is being manipulated. What I mean is that I see a property specified with the dot notation on the same level as an identifier and as such its name is just to remind us humans of its purpose, whereas a property accessed using bracket notation is important both to us and to the program since it specifies a data point.


Perhaps it implies that you've extracted those names into some kind of constant or configuration object or view model that you're using throughout the system; if they change, you change them in one place and the square bracket version keeps working.

I personally find it more useful to deal with forms using some kind of abstraction on top so I doubt I'd use either variations in anything other than a very simple page.


IIRC it has to do with backwards compatibility, but I believe that the property accessors have been there for quite a while so I don't know if it is even valid for most of the browser targeted today. It may be one of those old best practices that is no longer relevant with the exception of people targeting older browsers.


I had some linting tool yell at me about this recently. It said something like '''forms["formname"] better written as forms.formname'''




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: