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 trialMin-Chun Shih
5,221 PointsWhen adding remove and up button, why still need the if statement of 'event.target.tagName == 'BUTTON'
I don't understand why Joel doesn't delete the if statement for checking if the tagName is button? Because it works without the if statement. Thank you!
listUl.addEventListener('click', (event) => {
// if(event.target.tagName == 'BUTTON') {
if(event.target.className == 'remove') {
let li = event.target.parentNode;
let ul = li.parentNode;
ul.removeChild(li);
}
if(event.target.className == 'up') {
let li = event.target.parentNode;
let prevLi = li.previousElementSibling;
let ul = li.parentNode;
if (prevLi) {
ul.insertBefore(li, prevLi);
}
}
}
});
1 Answer
John Johnson
11,790 PointsThe short answer is: specificity. Having more specific rules for how and when JavaScript fires will make your code less prone to errors (in most cases).
The click event will trigger every time you click in the listUl, whether it does anything or not. Setting that first "if(event.target.tagName = 'button')" basically just makes sure that the only time this event will do an action is when you have clicked a button. In your case, you're right. This page works without it because the second delimiter, 'className = remove' only applies to the remove button itself.
Say for some reason you had to give one of the li elements the class remove. If you click it, it will be removed (or it's parent node, in this case). Well, depending on the specificity, you could accidentally remove the entire list! That example seems silly for this case, but in other websites, lack of specificity can cause big issues.
Hope this answers your question!