Fake Type Error

Hi! So I was working on one of the projects for the JS course and for some reason this code works on my personal code editor but not on the exercise as i get an: Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’).
Am i missing something?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PalindromeChecker</title>
    <link href="styles.css"></link>
    <script defer src="script.js"></script>
</head>
<body>
  <section id="container">
    <input id="text-input"></input>
    <button id="check-btn">Check</button>
    <div id="result"></div>
  </section>
</body>
</html>

JS:

const textBox = document.getElementById("text-input");
const checkBtn = document.getElementById("check-btn");


checkBtn.addEventListener("click", () => {
  alert("test");
});

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/build-a-palindrome-checker-project/build-a-palindrome-checker

Hi! What happens when you move your html link to your JavaScript to the end of the body element?

1 Like

Yup that solves it… So I guess the defer attribute doesn’t work here since the embedded preview doesn’t have an actual page load?

That’s what I’m thinking. With these tests it’s best to just keep things simple.

1 Like