The first example fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. This is also why the second example does work.
By placing your code in a document ready block it holds off executing it until the page has loaded.