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 Saving Names

Jesse Thompson
Jesse Thompson
10,684 Points

Im a little confused with the logic that is occuring

So heres my code for clicking buttons.

I just want to get this right. So because the if statement at the start targets a button and sets the appropriate constants in relation to the target, this means that even if I click edit on more than 1 user and click save on the first one, it still uses the constants created from the appropriate user instead of mixing them up and putting in the wrong input values?

That logic was a little confusing to me but I just want to make sure.

ul.addEventListener('click', (e) => {
     if (e.target.tagName === 'BUTTON') {
         const button = e.target;
         const li = button.parentNode;
         const ul = li.parentNode;
         if (button.textContent === 'remove') {
            ul.removeChild(li);
          } else if (button.textContent === 'edit') {
              console.log(event.target);
              //Creates input text element and places it before span. Then removes the span element.
              const span = li.firstElementChild;
              const input = document.createElement('input');
              input.type = 'text';
              input.value = span.textContent;
              li.insertBefore(input, span);
              li.removeChild(span);
              button.textContent = 'save';
         } else if(button.textContent === 'save') {
              console.log(event.target);
                   const input = li.firstElementChild;
                   let span = document.createElement('span');
                   li.insertBefore(span, input);
                   span.textContent = input.value;
                   li.removeChild(input);
                   button.textContent = 'edit';
               }
            }
     });```

1 Answer

Steven Parker
Steven Parker
231,248 Points

For each click event, the value of "e" will be the event object will indicate which button in the target property. Since all the other values are derived from that, they will all be appropriate for that specific element.