JavaScript JavaScript and the DOM Responding to User Interaction The Event Object

Anastasia Ponomarenko
Anastasia Ponomarenko
8,703 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

Zaid Khan
Zaid Khan
12,746 Points

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.