Search code examples
javaseleniumselenium-webdriverselenide

Selenide: How to get all active elements from ElementsCollection?


I'm trying to write an if statement for a collection but I've encountered with a problem. Just for instance, the following element has li tag that indicates whether the element is active:

<dl class="p-property-item">
<dt class="p-item-title" data-spm-anchor-id="42e07cb3WzvrLA">Color:</dt>
    <dd class="p-item-main">
        <ul id="j-sku-list-3" class="sku-attr-list util-clearfix" data-sku-prop-id="14" data-sku-show-type="none" data-isselect="true" data-spm-anchor-id="2114.10010108.1000016/B.i3.42e07cb3WzvrLA">
               <li class="active">
                    <a data-role="sku" data-sku-id="29" id="sku-2-29" href="javascript:void(0)" data-spm-anchor-id="2114.10010108">
                        <span data-spm-anchor-id="42e07cb3WzvrLA">White</span>
                    </a>
               </li>
        </ul>
                    <div data-role="msg-error" class="msg-error sku-msg-error" style="display: none;">
                        Please select a Color
                    </div>
    </dd>

I get all elements from a page and put it into collection:

@FindBy(how = How.CSS, using = "#j-product-info-sku > dl:nth-child(2) > dd > ul > li > a > span")
private ElementsCollection colorList;

public ElementsCollection getColor() { return colorList; }

But I have no idea how to get elements from the collection which have "active" li. I mean, how to get all active elements, is there any option to recognise them?

Note: All elements are visible so it's not relevant to filter by visible option.

I also used the java method that is mentioned here: Filtering an ElementsCollection

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

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



Condition hasChild = hasChildWithCondition(By.cssSelector("li"), Condition.text("active"));

if ((page.getColor().size() != 0) && (page.getColor().filterBy(hasChild))){
            //to do
        }

but in my case I get an error: Operator && cannot be applied to 'boolean','com.codeborne.selenide.ElementsCollection'


Solution

  • The solution is found: in order to put only active elements into the collection, I decided to ignore li elements with the class "disabled"

    ElementsCollection colorList = $$("#j-product-info-sku > .p-property-item > .p-item-main > ul > li:not(.disabled) > a");
    

    As of now, the collection contains only active elements