Answered: Error when trying to change innertext with a button in html and javascript

I was trying to make a tally counter with buttons but when i press the button i get this error:

Uncaught TypeError: Cannot set properties of null (setting 'innerText')

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src=./test.js></script>
        <link rel="stylesheet" href=./test.css></link>
    </head>
    <body>
        <h1 id="count_el">0</h1>
        <button id="increase" onclick="increase()">INCREASE</button>
        <button id="decrease" onclick="decrease()">DECREASE</button>
    </body>
</html>

And here is my JavaScript code:

const count_el = document.getElementById("count_el")
let count = 0

function increase(){
    count += 1
    count_el.innerText = count
}
function decrease(){
    count -= 1
    count_el.innerText = count
}

Solution 1:

Try and add defer into your script tag like so:

<script src=./test.js defer></script>

this will make the javascript load after the page has loaded and then the error should disappear.