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 last child from another </ul> list

Hello there,

I have two UL lists. I am trying to remove the last child from the second list, but somehow I am not able to do it. What am I doing wrong?

With my first button, by changing the UL value (ul[0] or ul[1] ) I am able to add elements to the first or second list. Here's a codepen I created:

https://codepen.io/DeMichieli/pen/EBmQWm

I do not understand why when I change the UL target (from [0] to [1]) it won't allow me to remove an element from the second list.

I appreciate your support!

1 Answer

Steven Parker
Steven Parker
229,645 Points

The "querySelector" function returns the first matching element, so if you call it on the document, you'll get the first list item that is a last child, which is the one in the first list. But then when you reference that list item in a call to "removeChild" on the second list, nothing happens because it is not a child of that list.

So instead of the whole document, you should select the list item from the specific list:

let li = ul.querySelector('li:last-child');  // ul, not document

That worked, Thanks Steven Parker !!!