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

Jamie Gobeille
Jamie Gobeille
Full Stack JavaScript Techdegree Student 5,703 Points

Alternative solution

I found it to read a little better to not have to do nested if statements in the event listener that determines what button is pressed and what action to proceed with.

I just assigned the buttons a class name when buttons are generated.

const editButton = document.createElement('button');
    editButton.textContent = 'edit';
    editButton.className = 'edit';
    li.appendChild(editButton);

    const removeButton = document.createElement('button');
    removeButton.textContent = 'remove';
    removeButton.className = 'remove';
    li.appendChild(removeButton);

Then instead of doing a two-step check process you only need to check for the class name. it reduces some code and is a little easier to read in my opinion.

ul.addEventListener('click', (e) => {
    const button = e.target.className;
    if(button === 'remove'){
        const li = e.target.parentNode;
        const ul = li.parentNode;
        ul.removeChild(li);
    } else if(button === 'edit') {
        console.log('edit mode');
    }
}); 

Does anyone see a problem in doing it this way?

1 Answer

Cory Harkins
Cory Harkins
16,468 Points

Hi Jamie!

Long answer short: No, there's nothing wrong with how you are accessing the buttons!

You could also use my personal fav in this situation: switch statements.

ul.addEventListener('click', (e) => {
    const button = e.target;
    switch(button.className) {
      case 'remove':
        const li = button.parentNode;
        const ul = li.parentNode;
        ul.removeChild(li);
        return;
      case 'edit': 
        console.log('edit mode');
        return;
      default:
        console.log('handle a default case');
        return;
    }
});