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) Traversing the DOM Sibling Traversal

let p = e.target.previousElementSibling - with an expression like this, it means the target is <p>, or no?

list.addEventListener('click', function(e) { if (e.target.tagName == 'BUTTON') { let p = e.target.previousElementSibling p.className = "highlight"; } });

I'm a little confused about this. Does e.target translate to the HTML element being targeted (let p)? From what I see in let p, p is just a variable. How does what it's set to know I want to select paragraph elements?

Trent Stenoien
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Trent Stenoien
Full Stack JavaScript Techdegree Graduate 21,632 Points

I'm an expert by no means, I just went through this course myself so take this with a grain of salt, but here's what I understand.

e.target is the info sent when you click. previousElementSibling of course refers to the previous element at the same level. You're correct, 'let p' is just an variable. It could as easily be 'let paragraph' or even 'let watermelon', it's just that the previous element is a <p> which is why the instructor chose that variable.

Does e.target translate to the HTML element being targeted (let p)?

e.target is the element being clicked. The conditional statement requires a button to be clicked to run though. If you look in the HTML, I believe the code is something like this:

<div>
   <p></p> /* previous Element */
   <button></button> /* e.target */
</div>

2 Answers

Steven Parker
Steven Parker
228,991 Points

e.target translates to the HTML element being targeted by the event.

Since this is a "click" event, the target is the element that was clicked on. And we know that the handler was attached to the list element, so the target must be that element or one of its descendants. And we also know from the if that serves as a filter that the target of the current event is a BUTTON element.

As long as the HTML structure remains consistent, we know all buttons within the list follow a paragraph, so the previousElementSibling will be a paragraph element.

Ok I'm starting to understand!! Thanks you two, referencing was just made A LOT more clear.