You are almost certainly running your code before the DOM is constructed. Try running your code in a window.onload
handler function (but see note below):
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
}
Another popular cross-browser solution is to put your block just before the closing