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 Interacting with the DOM Traversing the DOM Event Bubbling and Delegation

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,592 Points

Why did Reggie add an `if` statement?

In the video, Reggie added an if statement to his event handler:

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

In my code, I did not add an if statement and it worked fine:

taskList.addEventListener('mouseover', (e) => {
  e.target.textContent = e.target.textContent.toUpperCase();                     
  });

Why add an if statement? Will this address some other type of unintended consequence in the future?

2 Answers

Bella Bradbury
seal-mask
.a{fill-rule:evenodd;}techdegree
Bella Bradbury
Web Development Techdegree Student 14,361 Points

Stephen,

You're right on point! It's a good idea to add specificity in to ensure that your code continues to work the way you intended. Adding in a conditional like this can help with many little things down the line, like ensuring that a user can only press a page button and not the space around it when trying to navigate pages.

Happy coding!

Alexander Graham
Alexander Graham
7,568 Points

Hey, I agree that the 'if' statement is not needed, Reggie mentiones that 'taskList' is a reference to the div parent containing the 'ul' and the list items, however that's not the case... 'taskList' is a direct reference to the 'ul' already, so it should work perfectly without specifying you are triggering the event only with the list items.