40

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?

Mark Baker
  • 5,588
  • 2
  • 27
  • 25
user2167582
  • 5,986
  • 13
  • 64
  • 121

4 Answers4

78

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');
Jmr
  • 12,078
  • 4
  • 39
  • 33
  • 7
    This worked really well. Thanks. In case anyone else bumps into this and is wondering, get starts at 0, so to get the first element. `element.all(by.css('.dfdf')).get(0);` – usumoio Mar 24 '15 at 21:39
  • 4
    If you're looking to get the first element, you could do `element.all(by.css('.dfdf')).first()` per their [documentation](https://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.first) – Brandon Ward Mar 11 '16 at 01:29
19

If you want to get the first element then

element.all(by.css('.dfdf')).first();
element.all(by.css('.dfdf')).get(0);
Zaman Afzal
  • 2,009
  • 17
  • 23
3

Try this one. It will work:

element.all(by.css('.dfdf')).get(4).getText();
bwegs
  • 3,769
  • 2
  • 30
  • 33
ARB
  • 319
  • 3
  • 6
0

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

Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40