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 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,662 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,279 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
    ul.removeChild(li);
  //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") {
    alert("Edit");
  }
}); 
ywang04
ywang04
6,750 Points

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

button.tagName === "BUTTON"

You can refer to this similar question.

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.