diff --git a/lib/protractor.js b/lib/protractor.js index 590bda46b..80f1b6d04 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -285,6 +285,7 @@ var buildElementHelper = function(ptor) { /** * Get an element within the ElementArrayFinder by index. The index starts at 0. + * Negative indices are wrapped (i.e. -i means ith element from last) * This does not actually retrieve the underlying element. * * @alias element.all(locator).get(index) @@ -307,16 +308,17 @@ var buildElementHelper = function(ptor) { var self = this; var getWebElements = function() { return self.getWebElements().then(function(parentWebElements) { - if (index === -1) { - // -1 is special and means last - index = parentWebElements.length - 1; + var i = index; + if (i < 0) { + // wrap negative indices + i = parentWebElements.length + i; } - if (index >= parentWebElements.length) { + if (i < 0 || i >= parentWebElements.length) { throw new Error('Index out of bound. Trying to access element at ' + 'index:' + index + ', but there are only ' + parentWebElements.length + ' elements'); } - return [parentWebElements[index]]; + return [parentWebElements[i]]; }); }; return new ElementArrayFinder(getWebElements, this.locator_).toElementFinder_(); diff --git a/spec/basic/elements_spec.js b/spec/basic/elements_spec.js index 1e4b688a9..30f6296cd 100644 --- a/spec/basic/elements_spec.js +++ b/spec/basic/elements_spec.js @@ -366,18 +366,28 @@ describe('ElementArrayFinder', function() { expect(colorList.get(2).getAttribute('value')).toEqual('red'); }); + it('should get an element from an array using negative indices', function() { + var colorList = element.all(by.model('color')); + + browser.get('index.html#/form'); + + expect(colorList.get(-3).getAttribute('value')).toEqual('blue'); + expect(colorList.get(-2).getAttribute('value')).toEqual('green'); + expect(colorList.get(-1).getAttribute('value')).toEqual('red'); + }); + it('should get the first element from an array', function() { var colorList = element.all(by.model('color')); browser.get('index.html#/form'); - expect(colorList.first(0).getAttribute('value')).toEqual('blue'); + expect(colorList.first().getAttribute('value')).toEqual('blue'); }); it('should get the last element from an array', function() { var colorList = element.all(by.model('color')); browser.get('index.html#/form'); - expect(colorList.last(0).getAttribute('value')).toEqual('red'); + expect(colorList.last().getAttribute('value')).toEqual('red'); }); it('should perform an action on each element in an array', function() {