How to select last element of a particular class

Viewed 906

I was wondering why foo is logging a value while bar isn't. They seem to be syntactically identical too.

EDIT: This was an X-Y problem. My aim is to get the last element with the class foo and I tried to get this using last-child. I tried last-of-type to no avail.

const foo = document.querySelector(".some-element:last-child")
const bar = document.querySelector(".foo:last-child")

console.log('foo >>',foo)
console.log('bar >>',bar)
<article>
  <div class="foo">This `div` is first.</div>
  <div class="foo">This <span>nested `span` is last</span>!</div>
  <div>This <em>nested `em` is first</em>, but this <em>nested `em` is last</em>!</div>
</article>
<ul>
  <li class="some-element">1</li>
  <li class="some-element">2</li>
  <li class="some-element">3</li>
</ul>

1 Answers

You can use querySelectorAll() for select all element by class.

and for get the last element with class try this:

const bar = document.querySelectorAll(".foo")
console.log( 'bar >>', bar[bar.length - 1] )

Take a look at the Selectors Overview

Related