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>
The :last-of-type selector allows you to target the last occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content. ).
Yes, using :last-of-type with a class selector alone is very unintuitive; it is best used with a type selector unless you really want the last of any type to have that class.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With