Tatu Ulmanen's solution is correct, but it's worth discussing why. Here's a sort of quick-and-dirty explanation of what happens when a page is loaded
JavaScript and the DOM are two different things. In short, the DOM is a hierarchical data structure that represents the HTML page from which an API is exposed to JavaScript via objects like document
and others.
The DOM can be thought of as an unbalanced tree with an arbitrary (not fixed) amount of nodes at any level. When a page is loaded, each node/element/tag is evaluated and attached to the DOM tree in the order that it is encountered. When a script
element is encountered, it is full evaluated and executed before evaluating the rest of the HTML document.
Since your script
node is before the a
node that it is referencing, the a
node does not yet exist in the DOM tree, which is what is causing your issue. By moving the script
element after the nodes that is referencing (typically at the bottom of the page before the closing body
tag), these types of errors are avoided. Another common practice is to use the DOM's onload
event; this defers the execution of whatever function is assigned as its handler till the entire HTML page has been parsed/rendered into the DOM tree. The later method also allows you to include your script anywhere in the page you'd like (e.g.: in the head
).