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) Responding to User Interaction The Event Object

Anastasia Ponomarenko
Anastasia Ponomarenko
10,286 Points

Why do we need the If statement?

I have watched the video a few times, but I still do not understand why we need the if statement in the piece of code below:

listDiv.addEventListener('mouseover', (event) => { if (event.target.tagName == 'LI') { event.target.textContent = event.target.textContent.toUpperCase(); } });

Since event.target stores the exact element where the event occurred, why doesn't the code below apply the action to the exact <li> that we clicked instead of all children of listDiv?

listDiv.addEventListener('mouseover', (event) => { event.target.textContent = event.target.textContent.toUpperCase(); });

1 Answer

Hi, Anastasia Ponomarenko

We have made our listener on <ul> that's why In order to target specific li you need to check whether the target element is li or not.

If you won't put the condition, it's going to target every element inside and including itself as well.

In order to see this effect, remove the condition and hover on all the li elements including the ul element, you will see how it's going to affect all the elements including ul.