3

I'm trying to create a function to filter an ElementsCollection, with a condition on a child of each element instead of the element itself.

Here's what I came up with:

 public static ElementsCollection filterByChild(ElementsCollection elementsCollection, String childCssSelector,
        Condition condition) {

        Predicate<SelenideElement> childHasConditionPredicate = element -> element.$(childCssSelector).has(condition);
        elementsCollection.removeIf(childHasConditionPredicate);
        return elementsCollection;
    }

When calling this function like this:

myCollection = SelenideHelpers.filterByChild(myCollection, "a", Condition.text("http://www.link.com");

I'm getting the following error message:

java.lang.UnsupportedOperationException: Cannot remove elements from web page

I did not found any relevant informations on this error message that could be applied to my code. I would like to know why is this message appearing.

Eldy
  • 1,027
  • 1
  • 13
  • 31

1 Answers1

2

Check how SelenideElementIterator is designed:

@Override
public void remove() {
  throw new UnsupportedOperationException("Cannot remove elements from web page");
}

To make it work you need to create your custom condition like:

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static com.codeborne.selenide.Selenide.$$;


public static Condition hasChildWithCondition(final By locator, final Condition condition) {
    return new Condition("hasChildWithCondition") {
        @Override
        public boolean apply(WebElement element) {
            return element.findElements(locator).stream().anyMatch(child -> condition.apply(child));
        }

        public String toString() {
            return this.name
        }
    };
}

and then use it to filter:

ElementsCollection collection = $$(".parent");
Condition hasChild = hasChildWithCondition(By.cssSelector("a"), Condition.text("http://www.link.com"));
collection.filterBy(hasChild);
thi gg
  • 1,969
  • 2
  • 22
  • 47
dmle
  • 3,498
  • 1
  • 14
  • 22