user5617839
user5617839

Reputation:

Select last element of item in a list with the DOM

Without using jQuery (because I have yet to even start that section yet), and just using some good old JavaScript/DOM, how could I select the last element of an item in a list.

For example I have the following HTML:

<section id="container">
  <ul>
    <li class="first">one</li>
    <li class="second">two</li>
    <li class="third">three</li>
  </ul>
  <ol>
    <li class="first">one</li>
    <li class="second">two</li>
    <li class="third">three</li>
  </ol>
</section>

And I want to select this item and return it in the DOM: <li class="third">three</li> from the ol list. I understand that document.querySelector only selects the first element in the document, which would be document.querySelector('li.third'). How would I do the opposite and select the last?

Upvotes: 0

Views: 6675

Answers (3)

user2628521
user2628521

Reputation:

In order to get your item, you need to select properly. This means you need to be specific when you want to select .third

Sequence to select #container -> ol -> (either li:last-child or li.third)

document.querySelector("#container > ol > li.third");

Upvotes: 1

Shadof
Shadof

Reputation: 11

You can use document.querySelector('ol li:last-child')

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

You can use *:last-child if you have mixed child elements.

console.log(document.querySelector('#container *:last-child .third').textContent);
<section id="container">
  <ul>
    <li class="first">one</li>
    <li class="second">two</li>
    <li class="third">three</li>
  </ul>
  <ol>
    <li class="first">one</li>
    <li class="second">two</li>
    <li class="third">three (here)</li>
  </ol>
</section>

You can also grab the the last child by either:

  • #container *:last-child li:last-of-type or
  • #container *:last-child li:last-child

Upvotes: 4

Related Questions