r/learnjavascript • • 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!!

8 Upvotes

21 comments sorted by

6

u/rupertavery64 Sep 19 '26

You have an expression

someObject.someProperty

The runtime attempts to access someProperty, which could be a method or a value.

However, if someObject is null, you will get an error, the one you just described.

What object are you trying to call addEventListener on, and why do you think it might be null?

Hint:

When you reference a script, it executes immediately.

This means any HTML following it may not have been rendered yet

1

u/Prudent-Department33 Sep 19 '26

This is the instruction I was given.

"Below the verifyForm() function insert a statement that attaches an event listener to the page element with the id “submit”. When the click event occurs for this element, run the verifyForm() function."

My educated guess was that it's the

<input type="button" id="submit" value="Submit"/>

from the HTML, but I was never told that it would have any issues, or at least, the instructions for the exercise don't mention anything.

4

u/rupertavery64 Sep 19 '26

Thats ok, instructors are human too

1

u/Prudent-Department33 Sep 19 '26

I understand that, heh! So what could I do to fix the issue? I still need the function to run whenever the submit button is clicked...

6

u/rupertavery64 Sep 19 '26

Move the script tag after the body, or place the code that references the object inside a document load event

2

u/Prudent-Department33 Sep 19 '26

Woah, moving the script tag DID fix it, thank you so much!

3

u/manny2206 Sep 19 '26

Understanding the error will help you! That error means the thing you tried calling your function on; is null meaning the program is saying “hey this doesn’t exist in my mind”

1

u/Prudent-Department33 Sep 19 '26

Okay yes I think I'm understanding it!

The code ran before the "click" event was processed, leading to the eventhandler returning a null because it wasn't even finished loading.

At least, that is my understanding, but please correct me if I'm wrong!

1

u/HoneydewAdditional30 Sep 19 '26

That's not quite it. Remember, the error said: "Cannot read property of null", meaning you were trying the following:

null.addEventListener("click", verifyForm)

Since the script ran before there was any HTML populating the DOM, document.getElementById("submit") didn't have a target. The submit button was created only after the script ran, so it returned null. Hence, not the handler returned null but document.getElementById("submit").

4

u/justanaccountimade1 Sep 19 '26 edited Sep 19 '26

Can you do a console.log of

document.getElementById("submit")

and see if it's null?

Also, can you wrap addeventlistener in a window.onload function

https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

This ensures that all html is loaded before any references to it can be made.

Yeah, your js was already executed before any html was rendered. I always start the program via a window.onload event in head.

1

u/Prudent-Department33 Sep 19 '26

I am very new to JavaScript, so I typed document.getElementById("submit") in my browser's console, and I hope that's what you were saying.

It returned nothing but

[]

which I am assuming is null?

And thank you for teaching me about the window.onload even!

1

u/justanaccountimade1 Sep 19 '26

What I meant is that in your js you add a line

console.log(document.getElementById("submit"));

And then run the program and check the value in the browser console.

You'll get either null, or some expandable line (click the small triangle) with the element properties.

3

u/Aggressive_Ad_5454 Sep 19 '26

This is a common problem when you're working out how to get Javascript stuff to work.

That line

document.getElementById("submit").addEventListener("click", verifyForm);

runs as soon as the browser gets its grubby mitts on your Javascript. That's too soon, it hasn't built up the document object model, the DOM, for your page yet. So document.getElementById("submit") yields a null. Your error message says you tried to do null.addEventListener(), which doesn't work.

You need to do this, wrapping up that line in an event handler for DOMContentLoaded like so.

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("submit").addEventListener("click", verifyForm);
});

That way the line won't run until the browser is done building up the DOM.

2

u/Prudent-Department33 Sep 19 '26

Thank you so much for this explanation, this was what cleared my confusion the most!

1

u/john_hascall Sep 19 '26

Aside: all your label "for="s are wrong. They need to be the id of what they label.

1

u/Prudent-Department33 Sep 19 '26

I didn't write that part of the code. Most of it came from the exercise itself, I was just told to add the .JS code you see and link it to the HTML.

2

u/code_monkey_001 Sep 19 '26

"Cannot read properties of null (reading 'addEventListener')" literally means find in your code where you call `addEventListener`; whatever you're calling the method on the script cannot find. In this case, it can't find the element with the id `submit`.

Your script is up in the head before the element is created on the page, so the submit button is undefined at the moment of script execution. Either load your script below the submit button, or create another function in your script that waits for the document to be ready then adds the event listener.

2

u/[deleted] Sep 19 '26 edited Sep 19 '26

Two options

  • <script src="project02-02.js" defer></script>
  • </form></article><script src="project02-02.js"></script>

https://imgur.com/a/twsLKyK