Skip to content
This repository was archived by the owner on Jul 29, 2024. It is now read-only.

Commit ce5f494

Browse files
committed
feat(element): element.all now has 'first' and 'last' methods
Return the first or last element that matches a locator. Closes #171.
1 parent ef61662 commit ce5f494

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/protractor.js

+17
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,23 @@ var buildElementHelper = function(ptor) {
109109
return new webdriver.WebElement(ptor.driver, id);
110110
};
111111

112+
elementArrayFinder.first = function() {
113+
var id = ptor.findElements(locator).then(function(arr) {
114+
if (!arr.length) {
115+
throw new Error('No element found using locator: ' + locator.message);
116+
}
117+
return arr[0];
118+
});
119+
return new webdriver.WebElement(ptor.driver, id);
120+
};
121+
122+
elementArrayFinder.last = function() {
123+
var id = ptor.findElements(locator).then(function(arr) {
124+
return arr[arr.length - 1];
125+
});
126+
return new webdriver.WebElement(ptor.driver, id);
127+
};
128+
112129
elementArrayFinder.then = function(fn) {
113130
return ptor.findElements(locator).then(fn);
114131
};

spec/basic/findelements_spec.js

+14
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,20 @@ describe('global element function', function() {
328328
expect(colorList.get(2).getAttribute('value')).toEqual('red');
329329
});
330330

331+
it('should get the first element from an array', function() {
332+
var colorList = element.all(by.model('color'));
333+
browser.get('index.html#/form');
334+
335+
expect(colorList.first(0).getAttribute('value')).toEqual('blue');
336+
});
337+
338+
it('should get the last element from an array', function() {
339+
var colorList = element.all(by.model('color'));
340+
browser.get('index.html#/form');
341+
342+
expect(colorList.last(0).getAttribute('value')).toEqual('red');
343+
});
344+
331345
it('should export an isPresent helper', function() {
332346
expect(element(by.binding('greet')).isPresent()).toBe(true);
333347
expect(element(by.binding('nopenopenope')).isPresent()).toBe(false);

0 commit comments

Comments
 (0)