Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction Event Bubbling and Delegation

Heather Gray
Heather Gray
6,225 Points

Why wouldn't you choose the <ul> ancestor instead of the <div>?

In the Event Bubbling and Delegation video, the instructor is showing why it's helpful to choose an ancestor to put an event listener on rather than looping through each li item to put a listener on each one.

Example code I made up that is similar to video:

   <div class="myList">
    <p>P text</p>

In the above example, the instructor chose to use the div as the element to put the event listener on rather than the ul. I'm trying to understand why. Because this would mean that the event listener would trigger events for the <p> element too which isn't actually one of the list items.

1 Answer

You're right, the <ul> would be a better (closer) ancestor to attach the event to. I think the reason Gil didn't is because the ul is "naked" and doesn't have any class or id to give it enough specificity to select in the JS -- also, in the JS, Gil has already created a variable for the .list element, so he just used what's already ready to go.

If you were optimizing your site for performance, you would be right to maybe add a class to the ul, select it in your JS, and then put the click handler on it rather than the .list element.

Heather Gray
Heather Gray
6,225 Points

Thanks! A few videos later, he changed to target ul so I guess it was for example purposes. :)