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

Need clarification on event bubbling

.

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

A parent/ancestor element doesn't know how to apply that element to its children unless you explicitly give it instructions, and those instructions are defined in the function you pass as the callback in the event handler.

<div id="parent">
  <div>child 1</div>
  <div>child 2</div>
  <div>child 3</div>
</div>
const parent = document.getElementById("parent");
parent.addEventListener("click", function() {
  const children = parent.querySelectorAll("div");  
  for (child of children) {
    child.style.color = "red";
  }
})

In this example, whichever child you click, the event will bubble up to the parent. And the parents instructions is to set ALL the children's text color to red, regardless of which one was clicked, because those are the instructions that I gave it in my event handler.