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 JavaScript and the DOM (Retiring) Making Changes to the DOM Removing Nodes

Remove button just removing last button

I have tried the remove button, but it is removing only last item, not all. Here is my https://jsbin.com/binukaqivi/edit?html,js,output here is the code

var ul = document.getElementsByTagName("ul")[0]
var li = document.createElement("li");
var last = document.querySelector("li:last-child");

li.textContent = "I am new"
ul.appendChild(li);

var btn = document.getElementsByTagName("button")[0];


btn.addEventListener("click", function(){
  ul.removeChild(last);
})

1 Answer

Steven Parker
Steven Parker
231,269 Points

The JSbin code and the code shown here are different, but neither one seems complete.

But perhaps most pertinent to your question is this line:

  ul.removeChild(last);

Clearly, this line is intended to remove only the last item. If you want to remove other items, you might use a loop to select them and remove each one.

Or you could get rid of them all at once by just giving the list empty contents:

  ul.innerHTML = "";