How to select a single item in protractor
Asked Answered
A

4

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?

Anetta answered 26/11, 2013 at 20:47 Comment(0)
P
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');
Phytobiology answered 4/12, 2013 at 22:51 Comment(2)
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);Cupriferous
If you're looking to get the first element, you could do element.all(by.css('.dfdf')).first() per their documentationMelchizedek
C
19

If you want to get the first element then

element.all(by.css('.dfdf')).first();
element.all(by.css('.dfdf')).get(0);
Cid answered 22/11, 2016 at 21:12 Comment(0)
B
3

Try this one. It will work:

element.all(by.css('.dfdf')).get(4).getText();
Blamable answered 22/9, 2016 at 5:39 Comment(0)
M
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

Metzger answered 9/2, 2021 at 2:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.