Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 20,034 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
216,148 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.