DEV Community

Lusindiso Ntanjana
Lusindiso Ntanjana

Posted on

How to attach event handlers to dynamically created elements using vanilla JavaScript.

There are many ways to solve the JavaScript common error: “Cannot read property addEventListener of null” one of them being event delegation.

Are you trying/ or have you ever tried adding an event handler to a dynamically created element and get the error "Cannot read property addEventListener of null"? In this article I will walk you through on how to solve this common error.

The answer to your question (The element is already on the screen, so why is it returning null?) is simple that your element is not on the dom when your JS file runs. When your page loads also your JavaScript files will run, and the element will not be on the dom at that moment hence when trying to access the element with document.querySelector you will get a value of null. Now that you know why you are getting this error, I will walk you through how to solve this error using a common technique known as event delegation.

According to the learn.jquery.com, “event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future”. I know what you are thinking, yes this is the answer to our problem. But how do we do this event delegation?

As it stated above, we will look for an element that is a parent or or descendants that exist in the dom, meaning is added with html, and we will add the event to that element. Example you have an element with a class of container, we will add the event listener to that element. Then we add an if statement checking for the event target if it contains that particular element (eg if the element has an id of button, we check the id of the target event) and we add our event listener like:

document.querySelector(“.container”).addEventListner(‘click’, (event)=>{
    if(event.target.id === “button”){
        // Add your logic here…
    }
}

Enter fullscreen mode Exit fullscreen mode

Congratulations, you have just learned how to solve the JS common error : “Cannot read property addEventListener of null” using event delegation.

Top comments (0)