Question: How do I fix “TypeError: Cannot read properties of undefined” in JavaScript? #170507
-
BodyI'm working on a simple web app using vanilla JavaScript. I keep getting this error: let userInput = document.getElementById("username").value;The element definitely exists in the HTML. What could be causing this? Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
This error usually happens because document.getElementById("username") is returning null, and null.value throws TypeError: Cannot read properties of undefined document.addEventListener("DOMContentLoaded", () => { The ID doesn’t match Code runs before user interacts |
Beta Was this translation helpful? Give feedback.
This error usually happens because document.getElementById("username") is returning null, and null.value throws TypeError: Cannot read properties of undefined
Fix: Move your <script> tag to the end of the , or wrap your code in a DOMContentLoaded listener:
document.addEventListener("DOMContentLoaded", () => {
let userInput = document.getElementById("username").value;
console.log(userInput);
});
The ID doesn’t match
Double-check that your input has id="username" exactly (case-sensitive, no typos).
Code runs before user interacts
If you want the latest value, you might want to read it inside an event (like a button click).
document.getElementById("submitBtn").addEventListener("click", () => {