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

Why can't I choose last 'li' element from 'ul' using ul.lastChild?

Why can't I choose last 'li' element from 'ul' using 'ul.lastChild' property? I tried this, but it doesn't work:

//Remove item from the end of the list
removeItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.querySelector('li:last-child');
  //ul.removeChild(li);
  ul.removeChild(ul.lastChild); //WHY this doesn't work?
});

If 'ul' elemnet has other than 'li' child nodes, and that is the reason, how could I Identify them?

Thank you!

1 Answer

Steven Parker
Steven Parker
230,274 Points

Remember that lastChild returns the last child node.

A node doesn't have to be an element, it could also (and likely will) be text.

You probably intended to use lastElementChild.