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 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>
    <ul>
        <li>listItem1</li>
        <li>listItem2</li>
    </ul>
   </div>

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. :)