That error likely means the document.getElementById failed, as it means that el == null and/or undefined.
You can consider the DOM to be built, or at least constructed enough to access the elements on the page to be any point in the markup AFTER the element is declared. If you put that script BEFORE the element in the markup (like in <head></head>) the element won't exist yet on the DOM (document object model) so the document.getElementById can't see it yet.
That is why (along with speeding up page loads) it's become common practice to put scripting right before </body>, as at that point in the markup all the DOM elements in the markup exist. It's also why some people wait until the 'onload' event fires.
IF your script is before the element is in the markup, it's going to fail as that element hasn't been added to the DOM yet.
First alert will say "undefined" or "null" (depending on browser), second alert will say "Object DOMElement", "object HTMLDivElement" or something similar (again depending on browser)... I think that's the clearest way to show that in action. The first one fails because that element doesn't exist yet.
... and it's part of why more and more developers are moving scripting out of head, out of the middle of the markup, and to right before </body>.
Really though, this is why it's VERY hard to diagnose problems from snippets, we can't see where you have your script or are including the script in the markup; so we can't say if it's failing for that reason, or maybe some other reason.
-- edit -- sounds like you figured out what I meant. Good to hear.