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 DOM Scripting By Example Adding and Removing Names RSVP Checkbox

why use UL to add events to checkbox

I am trying to understand why Guil did the following.

ul.addEventListener('change', (e) => {
    const checkbox = event.target;
    const checked = checkbox.checked;
    const listItem = checkbox.parentNode.parentNode;

    if(checked){
        listItem.className = 'responded';
    }else{
        listItem.className = ';'
    }
}
  1. basically, at 3:00 on movie he says that the click bubbles up. so why we take refernece for ul and not checkbox, because UL will bubble upwards towards body not downloads to LI, yet in the above function the LI get targeted.

  2. why const checkbox = event.target; is used, why didn't we get reference for it like querySelector?

1 Answer

Steven Parker
Steven Parker
231,269 Points

It's the input that generates the event, the li is selected by traversal (the parent of the parent). The event bubbles up from the input to the ul. Placing the handler on the ul allows just one handler to take care of all the checkboxes. This is called a delegated handler.

Using event.target allows the handler to identify the particular checkbox that caused the event. You wouldn't know which one to select if you tried to use a selector method like "querySelector".