alecxe
alecxe

Reputation: 473833

Slicing elements in Protractor

In Protractor, we can get a single element from an array by index via:

var elements = element.all(by.css(".myclass"));
elements.get(1);
elements.first();
elements.last();

But, is it possible to slice out a subarray out of the array of elements in a similar fashion?

Ideally, we'd like to have something like:

var subelements = elements.slice(2, 5);
// subelements is also an ElementArrayFinder
// we can call "filter()", "map()" etc on subelements

I think we would need to extend ElementArrayFinder by defining a custom protractor.ElementArrayFinder.prototype.slice() method (similar to how it was done here).

I've also noticed this pull request, but it has not been merged and it is not active anymore.

Upvotes: 3

Views: 983

Answers (2)

Florent B.
Florent B.

Reputation: 42518

You can use slice directly on the resolved promise:

$$('a')
  .then(elements => elements.slice(3, 8))
  .then(elements => console.log("Count ", elements.length));

You cold also extend the ElementArrayFinder prototype:

protractor.ElementArrayFinder.prototype.slice = function(begin, end) {
  return this.then(elements => elements.slice(begin, end));
};

$$('a')
  .slice(3, 8)
  .then(elements => console.log("Count ", elements.length));

And with a filter:

$$('a')
  .filter((e, i) => i >= 3 && i < 8)
  .then(elements => console.log("Count ", elements.length));

Upvotes: 1

Xotabu4
Xotabu4

Reputation: 3091

There is no out-of-box solution i afraid. I believe you can implement slicing with .filter()

First that come to my mind:

function slice (arrayFinder, from, to) {
    return arrayFinder.filter(function(elem, index) {
        if (index >= from && index < to) {
            return true;
        }
    }
}

Upvotes: 3

Related Questions