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

Code working, but not understanding Remove button.

ul.addEventListener("click", (e) => {

  if (e.target.tagName === "BUTTON") {
    const li = e.target.parentNode;
    const ul = li.parentNode;
    ul.removeChild(li);
}
});

Can somebody break down, what is happening in the code.

So we create a event listener, we say if the tagName is BUTTON (where is button even created in capital?) const li = e.target.parentNode (what this?) const ul = li.parentNode (what this?) ul.removeChild(li); what is the child, what is the parent?

1 Answer

Steven Parker
Steven Parker
243,266 Points

Perhaps this will help:

  if (e.target.tagName === "BUTTON") {  // now we know the target is a button
    const li = e.target.parentNode;     // we know the button is inside a list item (li)
    const ul = li.parentNode;           // and the list item is inside an unsorted list (ul)
    ul.removeChild(li);                 // remove the child (li) from the parent (ul)

The "parent" is always the element that contains (surrounds) another element. The buttons are all inside (children of) list items, so the list item is the parent of the button. And the list items are all inside (children of ) unordered lists, so the ul is the parent of the list items.

And "BUTTON" (in caps) is just the way tag names are stored internally in the DOM for HTML elements. See the MDN page on tagName for more details.