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

[SOLVED] Using `:nth-child` pseduoselector to grab last unordered list item

Lets say I have this html in a web page:

      <ul class='list'>
        <li>grapes</li>
        <li>amethyst</li>
        <li>lavender</li>
        <li>plums</li>
      </ul>

I'm practicing using css selectors to grab the last list item, and I can't figure out what I'm doing wrong:

lastItem = document.querySelector('ul.list:last-child');

document.querySelector('ul.list'); works fine if I want to select the list, but why do I get null in response when I add the psuedoselector :last-child? What am I doing wrong?

Tobias Edwards
Tobias Edwards
14,458 Points

(Typo) You mean document.querySelector('ul.list > li:last-child')

1 Answer

Answering my own question: I was using :last-child wrong. I thought I should apply it to the parent element to select the parent element's last child, but that's not how it works. It modifies the actual element you're trying to select, so I should have used document.querySelector('li.list:last-child');, which you can think of as selecting the first instance of li that is the last child element.