This script cannot find “bannersize” unless I write <div id="bannersize"></div> before the javascript.
The error message:
Error “Uncaught TypeError: Cannot set property ‘innerHTML’ of null”
My code snippet:
<script>
function dropbox(menu){
this.tmpmenu = document.getElementById(menu);
this.tmpmenu.innerHTML = 'Hello'+this.tmpmenu;
}
bannersize = new dropbox('bannersize');
</script>
<div id="bannersize"></div>
It can’t find it because at the time the code is executed the element is not in the DOM. Script blocks are executed as soon as the browser sees the
</script>closing tag. Your code is before the element, so when it runs the HTML parser will not yet have encountered the element with the “id” you’re looking for.Put your code after the element, or run it in a “load” event handler for the document.