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 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(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
216,135 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.