r/learnjavascript • u/Prudent-Department33 • Sep 18 '26
Need to Learn! Error: "Cannot read properties of null (reading 'addEventListener')"
Hello! I don't usually post here, so I hope I'm in the right sub-reddit. I am currently in college and learning JavaScript. At this moment, I am trying to connect an addEventListener to a page element with the id "submit", and make it run the verifyForm() function. However, I get the error message "Cannot read properties of null (reading 'addEventListener')" whenever I load the code on my browser. How do I fix it? I have followed the instructions I was left to a T. Here is a snippet from the code for the .html file:
<script src="project02-02.js"></script>
</head>
<body>
<header>
<h1>
Hands-on Project 2-2
</h1>
</header>
<article>
<h2>Contact Information</h2>
<form>
<fieldset id="contactinfo">
<label for="nameinput">
Name
<input type="text" id="name" name="name" />
</label>
<label for="emailinput">
Email
<input type="text" id="email" name="email" />
</label>
<label for="phoneinput">
Phone
<input type="text" id="phone" name="phone" />
</label>
</fieldset>
<fieldset id="submitbutton">
<input type="button" id="submit" value="Submit"/>
</fieldset>
</form>
</article>
</body>And here is the code in the .js file:
function verifyForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let phone = document.getElementById("phone").value;
let check = (name !== "" && email !== "" && phone !== "") ? window.alert("Thank you!") : window.alert("Please fill in all fields.");
return check;
}
document.getElementById("submit").addEventListener("click", verifyForm);Any and all help is greatly appreciate it, as I am fascinated by JavaScript! If you need even more context for something, please let me know so that I can update the post accordingly.
Edit: Thank you everybody so much for your help! I will definitely come back if I ever get stuck with another problem I can't solve, you're lifesavers!!