Dymond
Dymond

Reputation: 2277

How to wait until an element is invisible

I Need to wait for an element to be NOT visible and found a couple of solutions for this, but none of them seems to work for me.

I think the problem is because I'm using PageObject Models. but I'm not complete sure.

 public static void WaitForElementToBeInvisible(this Browser browser, IWebElement element, int seconds = 30)
        {
            var wait = new WebDriverWait(browser.Driver, new TimeSpan(0, 0, seconds));
            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(element));
        }

But it returns error cannot convert from IWebElement to Selenium.By

Thanks in advance

Upvotes: 0

Views: 4306

Answers (4)

Roger Perkins
Roger Perkins

Reputation: 376

do { Playback.Wait(100); } while (_driver.FindElements(By.Id("elementId")).Count() > 0);

Upvotes: 0

Dymond
Dymond

Reputation: 2277

Thanks for all the answer, but solved it like this.

public static void WaitUntilInvisible(this Browser browser, By element, int seconds = 30)
        {
            var wait = new WebDriverWait(browser.Driver, new TimeSpan(0, 0, seconds));
            wait.Until(ExpectedConditions.InvisibilityOfElementLocated(element));
        }

Then used as By locator

By LoadingIcon = By.XPath(".//*[contains(@class, 'loading')]");

works like a charm :)

Upvotes: 0

Buaban
Buaban

Reputation: 5137

Your code is incorrect. It calls InvisibilityOfElementLocated which doesn't receive IWebElement as a parameter. See my example below.

public static bool WaitForElementToBeInvisible(this IWebElement element, int timeoutSecond = 10)
{
    IWait<IWebElement> wait = new DefaultWait<IWebElement>(element);
    wait.Timeout = TimeSpan.FromSeconds(timeoutSecond);
    wait.PollingInterval = TimeSpan.FromMilliseconds(300);
    try
    {
        wait.Until(!element.Displayed);
    }
    catch (WebDriverTimeoutException)
    {
        return false;
    }

    return true;
}

IWebElement div = driver.FindElement(By.Id("id"));
var result = div.WaitForElementToBeInvisible(5);

Upvotes: 1

Happy Bird
Happy Bird

Reputation: 1142

Short answer, this is not possible. The developers of Selenium have decided that there are no useful use cases for this.

If By locator is possible, you can use:

  public static void WaitUntilInvisible(this By locator)
        {
            try
            {
                if (Driver.FindElement(locator).Displayed)
                {
                    wait.Until(ExpectedConditions.ElementIsVisible(locator));
                }
        }

See also: Trying to convert IWebElement into a By element

Upvotes: 1

Related Questions