Search code examples
javascripthtmlgetelementbyid

Uncaught TypeError: Cannot read property 'clientHeight' of null Chrome 2020


This seems like a really simple problem but I just can't figure it out. In Chrome's Console log, I keep getting:

Uncaught TypeError: Cannot read property 'clientHeight' of null

This is my HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/styles.css">
    <script src="js/main.js"></script>
</head>
<body>
    <div id="deets">
        <h1>Document</h1>
        <p>Lorem ipsum...</p>
    </div>
    <canvas id="anim"></canvas>
</body>
</html>

And this is my JS code:

// 1. test main.js is linked to index.html
console.log('it works!!');

// 2. test #document code is available
console.log(document);

// 3. test .getElementById("deets") and get .clientHeight
console.log(document.getElementById("deets").clientHeight);

The First and Second tests work, but I can't figure out what's wrong with the Third. Element id="deets" keeps returning as a null.

Would appreciate any help so much. Thanks!


Solution

  • Something to try:

    1. Consider moving <script src="js/main.js"></script> before the </body>?

    This is because we're calling document.getElementById("deets") before the DOM elements are rendered.

    1. If we need to call <script src="js/main.js"></script> in the head, consider using the onload event.