Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Felipe Vidal
Felipe Vidal
10,360 Points

How do I set an event listener on an element that doesn't yet exist?

So when watching "Listening for events with addEventListener()" in "JavaScript and the DOM" i came up with this question when experimenting. I tried to set a list in html with no list items in it at the beginning, but when trying to set an event listener on a list item it turns out it doesn't run. Says the element is undefined, which is understandable because it does not exist at the time the event listener is set.

Does anyone know a solution to this problem?, say like adding the event listener after and element gets created?

2 Answers

Julian French
Julian French
3,257 Points

Yea, you could create a function that adds an event listener after the element gets created. For example:

function createEventListener() {
    if (liElement) {
        liElement.addEventListener('click', function() {
            console.log('success');
        });
    } else {
            console.log(Error('fail'));
    }
}
Felipe Vidal
Felipe Vidal
10,360 Points

Thanks buddy, that made it work :)

Julian French
Julian French
3,257 Points

Dope! I'm glad it worked for you!