0

My code (simplified):

HTML:

<!DOCTYPE html>
<head>
<title>Title</title>
<script type="text/javascript" src="main.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body align="center">
<div id="container">
<h1>Title</h1>
</div>
</body>
</html>

JS:

const container = document.querySelector('#container');

for (i = 0; i < 16; i++) {
    for (let x = 0; x < 16; x++) {
        const cellSize = 512 / 16;
        const cell = document.createElement('div');

        cell.style.width = cellSize + 'px';
        cell.style.height = cellSize + 'px';
        container.appendChild(cell);
    }
};

Console:

Uncaught TypeError: Cannot read property 'appendChild' of null

What have I done wrong here? It might just be my browser (I'm using Chrome). Is it because the constants are being referenced inside the for loop?

snaldi
  • 101
  • 1
  • 2
  • 9
  • Your code is executing before the document is ready, so the `#container` element doesn't exist yet. Try `console.log()` the `container` to see. – John Ellmore Mar 15 '18 at 19:28

2 Answers2

0

Your document is not ready yet. You need to wait for the document to be rendered before applying JavaScript to it.

Therefore you should call your script after the HTML.

<!DOCTYPE html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body align="center">
<div id="container">
<h1>Title</h1>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Ryan Schaefer
  • 3,047
  • 1
  • 26
  • 46
-1

You should use getElementById() instead to retrieve your div. Try this:

var container = document.getElementById('container');

for (i = 0; i < 16; i++) {
    for (let x = 0; x < 16; x++) {
        var cellSize = 512 / 16;
        var cell = document.createElement('div');

        cell.style.opacity = 0.0;
        cell.style.width = cellSize + 'px';
        cell.style.height = cellSize + 'px';
        container.appendChild(cell);
    }
};

Also make sure the script runs AFTER loading the html.

GSinghLDN
  • 161
  • 8