Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select last element of a particular class

Tags:

javascript

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>
like image 646
reactor Avatar asked Jun 09 '19 17:06

reactor


People also ask

How do you select the last element in CSS?

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. ).

Can you use last of type on a class?

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.

How do you select an element from a 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.


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

like image 166
AmirBll Avatar answered Nov 15 '22 05:11

AmirBll