5

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>
reactor
  • 1,200
  • 9
  • 22
  • 1
    why is this a surprise? None of the `.foo` elements are the last child of their parent. – Robin Zigmond Jun 09 '19 at 17:33
  • 1
    Which `.foo` is the last child of its parent? – Ry- Jun 09 '19 at 17:33
  • I see. I suppose my aim is completely different. How would I select the last element with class `foo`? – reactor Jun 09 '19 at 17:34
  • 2
    I don't think you can do that with CSS selectors. You'd need some sort of "look-ahead" in the DOM tree, which selectors don't provide. – melpomene Jun 09 '19 at 17:38
  • 1
    XPath could do this, but XPath sucks at selecting elements by class. Sigh. – melpomene Jun 09 '19 at 18:19
  • @reactor Sometimes an alternative is to put your last-element styles in a `.foo` rule, then undo them in a `.foo ~ .foo` rule (`.foo ~ .foo` being equivalent to `:not(:last-of-class(.foo))` if the `:last-of-class(.foo)` selector you were looking for existed). – Ry- Jun 10 '19 at 00:45

1 Answers1

4

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

AmirBll
  • 1,020
  • 1
  • 12
  • 25