0

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>

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks You Pointy , I edit it to and it's work :) <script> window.onload = function(){ function dropbox(menu){ this.tmpmenu = document.getElementById(menu); this.tmpmenu.innerHTML = 'Hello'+this.tmpmenu; } bannersize = new dropbox('bannersize'); } </script> <div id="bannersize"></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.