user2167582
user2167582

Reputation: 6368

How to select a single item in protractor

Usually in protractor you can select singular element with:

element(protractor.By.css('#fdfdf'));

Occasionally you get something like this:

element(protractor.By.css('.dfdf'));

which potentially has more than one element. What's the correct way to select an index from a locator that locates multiple elements, and still contain the protractor's methods for sending Keys?

Upvotes: 40

Views: 40785

Answers (4)

Sergey Pleshakov
Sergey Pleshakov

Reputation: 8948

I don't know why xpath is so much underestimated but you can solve thousands of problems with it, including this one

let elem = element(by.xpath('(//div//a)[3]'))

You can specify the number of element to use. Keep in mind the numbers start from 1, not 0 as usually in js

Upvotes: 0

ARB
ARB

Reputation: 327

Try this one. It will work:

element.all(by.css('.dfdf')).get(4).getText();

Upvotes: 3

Zaman Afzal
Zaman Afzal

Reputation: 2109

If you want to get the first element then

element.all(by.css('.dfdf')).first();
element.all(by.css('.dfdf')).get(0);

Upvotes: 19

Jmr
Jmr

Reputation: 12108

You can get an indexed element from an array returned with

// Get the 5th element matching the .dfdf css selector
element.all(by.css('.dfdf')).get(4).sendKeys('foo');

Upvotes: 78

Related Questions