Fixed: TypeError: $(…) is null

Recently I had to use Prototype JS to listen to an onchange event on a select box and toggle the display of some other elements on the page accordingly.

The code worked fine in Firebugs’ console, but I was getting this error when I had added my code to the HTML:

TypeError: $(...) is null

Usually this error means that the library hasn’t been included, so the $() function doesn’t exist, but the library definitely was included on the page.

After some research, I came across the solution – always put code which observes on a specific DOM element after the element has been created. I had put my JavaScript before the HTML it was working with. Moving it after the same HTML made it work. That also explains why it worked perfectly in the console – because the DOM has already been loaded in it’s entirety.

A simple mistake to make perhaps, but it’s a crucial difference between browser languages like JavaScript and interpreted server-side languages like PHP.