document.getElementBy Whatever I Want

During re-factoring of a dreadful legacy app, I often came across javascript like this:

document.getElementById('firstName');

with HTML like this:

<input type="text" name="firstName" />

I was confused as to how this ever worked and made it into production. I always assumed that getElementById would get an element by it’s Id. This is for the most part true. However, in earlier versions of IE, getElementById would also work with name attributes. It’s this kind of “IE Logic” that did immeasurable damage to both development practices and the web at large. Even as a convenience feature, it should not have been used. When a function explicitly says what it does in it’s name, don’t use it any other way.

In hindsight, if you were of the opinion that “we only use IE here so it doesn’t really matter”, you were wrong. It does matter.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.