How to fix: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I was working on the mapping of items that I would use for creating a portfolio for a website and I encountered this TypeError about my addEventListener not working:
The error message "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')" suggests that when the JavaScript is trying to add an event listener, the element it's trying to attach the event to doesn't exist or hasn't been found in the DOM.
However, in this case, the error message is a bit misleading, because document.addEventListener
is a standard method and should not be null. The issue is likely not with document.addEventListener
itself, but with the line of code where you are adding an event listener to an element with class .close
. If this script is running before the DOM is fully loaded, it won't find the element with class .close
, and document.querySelector('.close')
will return null.
My original code was this:
Here's a corrected version of your script, which ensures that the event listener for the close button is added after the DOM content has loaded:
🛠️ Key Changes Include:
Refactoring the logic to go like this to render static content first, then scripts with DOM Load updates later for the order of operations to take effect:
Static content first (div’s)
Scripts
Styles
A refactor of the DOMContentLoaded call to this:
Looking for more resources?
Read more related content here:
-
Automating Code Generation with OpenAI GPT Agents: A Developer's Journey to Efficiency
-
Thankful for the AWS Community Builders Program & Building + AWS Step Functions 101
-
AWS: Predicting Stock Prices Using AI & NO CODE!
-
Want to Learn How to Code? Discover the Top 4 Platforms to Kickstart Your Software Engineer Journey of Coding
-
Turn Your AI Model into a Real Product (Amazon SageMaker, API Gateway, AWS Lambda, Next.js, Python)
-
Launch your own LLM (Deploy LLaMA 2 on Amazon SageMaker with Hugging Face Deep Learning Containers)
Snag my 7 Days of Development ebook here:
I'll send you a FREE copy of my 7 Days of Development Ebook to get you started writing Python scripts, Node.js functions, Next.js apps, and building in the cloud!
