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

How does const checkbox = e.target; know to target checkboxes on the ul.event handler for "change"?

In this section of code for const checkbox creates an input checkbox,

const input = document.getElementById("name");
const form = document.getElementById("fanPage");
const ul = document.getElementById("list");

form.addEventListener("submit", (e) =>{
    e.preventDefault();

    let  text = input.value;        
    const li = document.createElement("li");
    const label = document.createElement("label");
    const checkbox = document.createElement("input");
          checkbox.type = "checkbox";

         li.appendChild(label);
         label.textContent = text;
         label.appendChild(checkbox);

        input.value = "";
        ul.appendChild(li);
        li.style.color = "blue";
});

But here, const checkbox = e.target; how does it target all checkboxes when the const checkbox in the above handler is on its own separate scope?

ul.addEventListener("change", (e)=>{
    const checkbox = e.target;  
    const checked = checkbox.checked; 
    const li = checkbox.parentNode.parentNode;
        if(checked){
            li.className = "select";
        }else{
            li.className = "";
        }
});

1 Answer

Steven Parker
Steven Parker
243,656 Points

The listener is being placed on the "ul", so it will respond to any element inside it as the events "bubble up".

The reason only the checkboxes trigger the handler is because only input elements generate "change" events.

Oooh, now it makes sense, because "change" only triggers input elements, thanks , Steven