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:

Code Snippet: mapping of items with addEventListener (not working)


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:

Code Snippet: mapping of items with addEventListener (not working)

🛠️ 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:

Code Snippet: DOMContentLoaded specs



Looking for more resources?

Read more related content here:



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!


7 Days of Development Ebook
Previous
Previous

How to fix the OpenAI API Key Error: “You exceeded your current quota, please check your plan and billing details” or “insufficient_quota”

Next
Next

Google Colab disk space vs Google Drive disk space - What’s the difference?