Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: Uncaught TypeError: Cannot set property 'innerHTML' of null [duplicate]

I keep on getting the error "Uncaught TypeError: Cannot set property 'innerHTML' of null" when I try to run this program in chrome. I do not now what I am doing wrong, and and any help would be appreciated.

<!DOCTYPE html>
<html>
<head>
</head>
<script>
    var x = "hey";
    var counter = 1;
    var button = document.getElementById("button");
    var div = document.getElementById("box");
    var text = document.getElementById("text");
    var sound = document.getElementById("sound");
    var array=[ "thanks for clicking", "keep on clicking", "click one more time", "why do you keep on clicking me?", "stop clicking me!"];
function thing(file){
    var y = array[Math.floor(Math.random() * array.length)];
        if (x == y){
            while (y == x){
                var y = array[Math.floor(Math.random() * array.length)];
        }   
        }
    form1.text.value=y;

    x = y;
sound.innerHTML = "<embed src=\""+file+"\"hidden=\"true\"autostart=\"true\" loop=\"false\"/>";

}
</script>
</head>
<body>
<form name="form1">
<input type="button" id="button" value="click" onClick="thing('sound.mp3')" />
    <input type="text" id="text" value="hey" />
</form>
<div id="sound">
<p>
</p>
</div>
</body>
</html>
like image 601
James Dorfman Avatar asked Dec 19 '13 23:12

James Dorfman


People also ask

How to fix Cannot set properties of null setting innerHTML')?

To solve the "Cannot set property 'innerHTML' of null" error, make sure the DOM element you're setting the innerHTML property on exists. The error most commonly occurs if you use the getElementById() method and pass it an id that is not present in the DOM.

What does uncaught TypeError Cannot set properties of null setting innerHTML ') mean?

Uncaught TypeError: cannot set property 'innerHTML' of null This means we are trying to apply a property or a function to a value that does not support a property or function. In this case, we're trying to set the value of innerHTML on an element that is equal to null. Null values do not have an innerHTML property.


1 Answers

Wait for the window to load:

window.onload = function()
{
    //yourJSCodeHERE
}

or move your JS after the </body> tag.

like image 146
Cilan Avatar answered Oct 12 '22 14:10

Cilan