[javascript] Uncaught TypeError: Cannot set property 'onclick' of null

I'm having problems making my window alert pop up with a simple checkbox and can't for the life of me figure out why. Here's the basic Javascript and HTML:

_x000D_
_x000D_
var blue_box=document.getElementById("color-blue");_x000D_
function colorFunction() {_x000D_
    window.alert("This color is blue!");_x000D_
}_x000D_
_x000D_
blue_box.onclick=colorFunction;
_x000D_
<form action="" method="POST" id="form">_x000D_
    <fieldset>_x000D_
        <legend> Form!</legend>_x000D_
        <ul>_x000D_
            <li><label><input type="checkbox" _x000D_
                    name="color" _x000D_
                    value="blue" _x000D_
                    id="color-blue" />_x000D_
                    blue</label>_x000D_
                </li>_x000D_
         <li><label><input type="checkbox" _x000D_
                    name="color"  _x000D_
                    value="red" _x000D_
                    id="color-red" />_x000D_
                    red</label>_x000D_
                </li>_x000D_
  <li><label><input type="checkbox" _x000D_
                    name="color" _x000D_
                    value="yellow" _x000D_
                    id="color-yellow" />_x000D_
                    yellow </label>_x000D_
                </li>_x000D_
            </ul>_x000D_
        </fieldset>_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Which throws: Uncaught TypeError: Cannot set property 'onclick' of null under

blue_box.onclick=colorFunction;

Are there any visible reasons for this error in my code?

This question is related to javascript events handler

The answer is


So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.

I assume it's because it makes sure there's something to reference, but I am not entirely sure.


Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null


Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.


Wrap code in

window.onload = function(){ 
    // your code 
};

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.


"blue_box" is null -- are you positive whatever it is with "id='blue'" exists when this is being run?

try console.log(document.getElementById("blue")) in chrome or FF with firebug. Your script might be running before the 'blue' element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload).