Wait for multiple elements to become invisible Selenium Java

I am using this code to check for invisibility:

WebDriverWait wait = new WebDriverWait(driver,40);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(<some xpath>)));

This works perfectly if there is only one element corresponding to the xpath in the webpage.

I have three in the webpage which I am trying to write a script for, and I need selenium to wait for all three.

Note: I am not using absolute xpath.

Upvotes: 1

Views: 2541

Answers (1)

Pradhan
Pradhan

Reputation: 508

ExpectedConditions.invisibilityOfElementLocated check for the first element. In your case you could write your own implementation of ExpectedCondition where you have to check if the object is displayed for each of the element which is found.

For Example (not tested) :

private static void waitTillAllVisible(WebDriverWait wait, By locator) {

    wait.until(new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver driver) {

            Iterator<WebElement> eleIterator = driver.findElements(locator).iterator();
            while (eleIterator.hasNext()) {
                boolean displayed = false;
                try {
                    displayed = eleIterator.next().isDisplayed();
                }
                catch (NoSuchElementException | StaleElementReferenceException e) {
                    // 'No such element' or 'Stale' means element is not available on the page
                    displayed = false;
                }
                if (displayed) {
                    // return false even if one of them is displayed.
                    return false;
                }
            }
            // this means all are not displayed/invisible
            return true;
        }
    });
}

Upvotes: 3

Related Questions