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

About removeChild

<div class="container">
 <ul class="list reset">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
 </ul>
 <button class="btn">Delete</button>
</div>

var container = document.querySelector (".container");
var list = document.querySelector(".list");
var li = document.querySelectorAll(".list li");
var btn = document.querySelector(".btn");

container.addEventListener ("click", (e) => {
  if (e.target.tagName === "LI") {
    let li = e.target;
    list.removeChild(li);
  }
});

btn.addEventListener ("click",() => {
  list.removeChild(li);
});

After practicing "Event Bubbling" and back to try simple btn.addEventListener to control removeChild it always got fail, it show "The node to be remove is not a child of node"...but li is under ul, why is it not working ? I got confuse ..

1 Answer

Steven Parker
Steven Parker
220,501 Points

The "querySelectorAll" function returns a collection, not a single element, so what's in "li" is not a valid argument to "removeChild".

If you change it to "querySelector" instead, the button will remove the first item.

And if you move the assignment into the handler, it will continue to remove the topmost item on subsequent clicks.

Thank you Steven, If I change it to "querySelector" it works, but why it only remove once.
Is that mean addEventListener always active once ? If it need to keep acting should always combine with for loop or event bubbling?

Steven Parker
Steven Parker
220,501 Points

It only removes the first item because "li" is assigned only once when the program loads. That's why I suggested moving that assignment into the handler where it will continue to pick the topmost item on each click.