TinaSky
TinaSky

Reputation: 39

In webdriverios, how to select the last element with the same classname?

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

Answers (2)

Vasyl
Vasyl

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

Kevin Lamping
Kevin Lamping

Reputation: 2269

You can use a :last-child CSS pseudo-selector:

const elem = $('.example:last-child')

Upvotes: 1

Related Questions