Reputation: 39
I have multiple elements with the same class name and I want to select the last one.
I tried the following method but they do not work. Any help would be greatly appreciated.
const elem = $('.example')[-1]
const elem = $('.example[-1]')
const elem = $('.example').last()
Upvotes: 0
Views: 1262
Reputation: 11
Also :last-of-type
might be useful :) For example:
// Get the last <p> element
const elem = $('p:last-of-type')
console.log(elem)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
<h1>A Title</h1>
<p>Paragraph 1.</p>
<p>Paragraph 2.</p>
<p>Paragraph 3.</p>
<img src="...">
</article>
Upvotes: 1
Reputation: 2269
You can use a :last-child
CSS pseudo-selector:
const elem = $('.example:last-child')
Upvotes: 1