Uncaught TypeError: Cannot set property 'onclick' of null

user1279662 picture user1279662 · Mar 19, 2012 · Viewed 152.3k times · Source

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:

var blue_box=document.getElementById("color-blue");
function colorFunction() {
    window.alert("This color is blue!");
}

blue_box.onclick=colorFunction;
<form action="" method="POST" id="form">
    <fieldset>
        <legend> Form!</legend>
        <ul>
            <li><label><input type="checkbox" 
                    name="color" 
                    value="blue" 
                    id="color-blue" />
                    blue</label>
                </li>
	        <li><label><input type="checkbox" 
                    name="color"  
                    value="red" 
                    id="color-red" />
                    red</label>
                </li>
		<li><label><input type="checkbox" 
                    name="color" 
                    value="yellow" 
                    id="color-yellow" />
                    yellow </label>
                </li>
            </ul>
        </fieldset>
    </form>

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?

Answer

maximkou picture maximkou · May 24, 2013

Wrap code in

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