1

I have an index.html file that has

<html>
    <head>
        <script src="2-4.js"></script>
    </head>
</html>

and a 2-4.js file that has

var div,
    container = document.getElementById('container')
for (var i = 0; i < 5; i++) {
    div = document.createElement('div')
    div.onclick = function() {
        alert('This is box #' + i)
    }
container.appendChild('div')
}

They're in the same folder. When I open index.html in Chrome and inspect, I see "Uncaught TypeError: Cannot read property 'appendChild' of null at 2-4.js:11" in the console. I looked up some SO questions involving that error but didn't find them helpful. Does anyone have an idea what's going on? Am I running the program wrong?

JohnDoeVsJoeSchmoe
  • 671
  • 2
  • 8
  • 25

1 Answers1

1

I think you're trying to do this:

<html>
<head>
</head>
<body><div id="container"></div></body>
<script>

var container = document.getElementById('container');
for (var i = 0; i < 5; i++) {
    var div = document.createElement('div');
    div.onclick = function() {
        alert('This is box #' + i);
    }
    container.appendChild(div);
}

</script>
</html>

Basically the message says that null (as in, no object ref) does not have a property or method 'appendChild', which is obvious, because document.getElementById('container') will return nothing, as it can't find such an element, simply because its not there...

ChrisF
  • 134,786
  • 31
  • 255
  • 325
user1515791
  • 675
  • 4
  • 20
  • You need to load the script at the end of the body or use `window.onload`. – Barmar Jun 25 '18 at 19:52
  • @Barmar, its formatted just the way the OP showed - the javascript is in a seperate file – user1515791 Jun 25 '18 at 19:53
  • Putting it in a separate file doesn't help. You need to put the ` – Barmar Jun 25 '18 at 19:55
  • Or the script need to put the code that calls that into a `window.onload` function. Read the duplicate question for details. – Barmar Jun 25 '18 at 19:56
  • You're right. too soon to answer :) – user1515791 Jun 25 '18 at 19:57