JavaScript Error: Uncaught TypeError: Cannot read property ‘addEventListener’ – Solved!

JavaScript Event Listener Error: Cannot Read Property ‘addEventListener’

I’m working on building some JavaScript event listeners for a project.

While working on a demo based on this YouTube Video. I got an error that took me a couple of minutes to figure out.

I encountered this error, JavaScript Event Listener Error: Cannot Read Property ‘addEventListener’, while working through this video on creating JavaScript Event Listeners.

If you follow this video and have issues getting your JavaScript Event Listener to work then read on to my solution below to see how I fix my below.

JavaScript Event Listener Example Video

The JavaScript Code to Add an EventListener

const grandparent = document.querySelector(".grandparent")

const parent = document.querySelector(".parent")

const child = document.querySelector(".child")

 grandparent.addEventListener('click', e => {

    console.log(e)
     }) 
 

JavaScript Uncaught TypeError: Cannot read property ‘addEventListener’ of

Solution: Move JavaScript to End of File

The root cause of the error is that if we load the JavaScript file before the DOM element loads then the const reference to grandparent class fails as it has not yet been loaded in to the DOM as the web page is rendering.

By simply moving the JavaScript tag to the end of the web page, it now loads after the div tag elements in the DOM so they can be referenced in the JavaScript and available in memory.

I hope this makes sense and that it helps somebody! 🙂

~Cyber Abyss