Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (19.7k points)

I have tried using ExpectedConditions.not() to invert ExpectedConditions.presenceOfElementLocated(), hoping that it would mean "expect that there is not a presence of the specified element". My code is like so:


new WebDriverWait(browser, 1).until(



However, I found that even doing this, I get a TimeoutException caused by a NoSuchElementException saying that the element "foo" does not exist. Of course, having no such element is what I want, but I don't want an exception to be thrown.

So how can I wait until an element no longer exists? I would prefer an example that does not rely on catching an exception if at all possible (as I understand it, exceptions should be thrown for exceptional behavior).

1 Answer

0 votes
by (62.9k points)

You can also use -

new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(locator));

If you go through the source of it you can see that each NoSuchElementException and staleElementReferenceException are handled.

/**   * An expectation for checking that a web-element is either invisible or not

   * present on the DOM.


   * @param locator used to find the element


  public static ExpectedCondition<Boolean> invisibilityOfElementLocated(

      final By locator) {

    return new ExpectedCondition<Boolean>() {


      public Boolean apply(WebDriver driver) {

        try {

          return !(findElement(locator, driver).isDisplayed());

        } catch (NoSuchElementException e) {

          // As the element is not present in DOM, it returns true. The

          //this try block detects whether the element is present but is invisible.

          return true;

        } catch (StaleElementReferenceException e) {

          // The stale element reference implies that element is no longer visible, hence returns true.

          return true;



If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium course

Browse Categories