You must be running your code from within the <head>
tag. document.body
doesn't exist at that point. You have to wait for the DOM to be ready. You can do that using something like jQuery's $(document).ready()
http://jsfiddle.net/L83mL/
Credit to https://stackoverflow.com/users/1013842/david and https://stackoverflow.com/users/400654/kevin-b