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 trial

JavaScript DOM Scripting By Example Editing and Filtering Names States of the Application

Sam Finn
Sam Finn
868 Points

if statement for button event handler

why do you have 2 "if" declarations in a row for the ul.eventlistener for the buttons remove/edit.

sorry for the confusion i just thought it had to be "if" followed by "else if"

3 Answers

Stan Day
Stan Day
36,802 Points

If statements can be used on their own or optionally with one or multiple if else statements and optionally an else statement at the end.

Chris Davis
Chris Davis
16,280 Points

This was my solution instead of adding a nested if statement...

ul.addEventListener("click", (e) => {
  const button = e.target;
  const li = e.target.parentNode;
  const ul = li.parentNode;
  //Check to see if the element with a type of button with the text content "Remove" was clicked
  if(button.tagName === "BUTTON" && button.textContent === "Remove") {
    //remove li from page
  //Check to see if the element with a type of button with the text content "Edit" was clicked
  } else if(button.tagName === "BUTTON" && button.textContent === "Edit") {
6,762 Points

You repeat below statement twice, which is not the best practise.

button.tagName === "BUTTON"

You can refer to this similar question.

Vegard Korsmo
Vegard Korsmo
Courses Plus Student 16,895 Points

I will say it make sense to use two different if declarations here in case one want to extend the application later on. Now it is two buttons, but if one need X more buttons for some reason you can just add X more 'else if' with only the "else if (button.textContent === 'nameOfExteraButtons')-part.

I was also first thinking about using the solution Chris Davis shows here. It will of course still work if one add more buttons, but you will have to repeat the 'button.tagName === "BUTTON"-part' for each new button added.