Skip to main content
SeleniumDecoded
Chapter 4 · Lesson 4 of 7 Waits & Synchronization
On this page

Expected Conditions

Use built-in expected conditions for common wait scenarios like visibility, clickability, and text presence.

Selenium 3 & 4 Stable 3 min read · Updated · Verified against Selenium 4.52.0
Before you start: Explicit Waits

Expected Conditions are pre-built wait conditions for common scenarios. They handle the complexity of checking element states, so you don’t have to write custom logic for every wait.

Visibility Conditions

Waiting for Visibility
Selenium 3 & 4 Stable
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be visible (present + displayed)
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("content"))
);
// Wait for already-found element to be visible
WebElement foundElement = driver.findElement(By.id("popup"));
wait.until(ExpectedConditions.visibilityOf(foundElement));
// Wait for all matching elements to be visible
List<WebElement> items = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("item"))
);
// Wait for element to become invisible
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading")));
// Wait for element with text to become invisible
wait.until(ExpectedConditions.invisibilityOfElementWithText(
By.className("status"), "Loading..."
));
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
# Wait for element to be visible (present + displayed)
element = wait.until(
EC.visibility_of_element_located((By.ID, "content"))
)
# Wait for already-found element to be visible
found_element = driver.find_element(By.ID, "popup")
wait.until(EC.visibility_of(found_element))
# Wait for all matching elements to be visible
items = wait.until(
EC.visibility_of_all_elements_located((By.CLASS_NAME, "item"))
)
# Wait for element to become invisible
wait.until(EC.invisibility_of_element_located((By.ID, "loading")))
# Wait for element with text to become invisible
wait.until(EC.invisibility_of_element_located((By.CLASS_NAME, "status")))
const { until } = require('selenium-webdriver');
// Wait for element to be visible
const element = await driver.wait(
until.elementLocated(By.id('content')),
10000
);
await driver.wait(until.elementIsVisible(element), 10000);
// Wait for element to be invisible/removed
await driver.wait(until.elementIsNotVisible(element), 10000);
// Wait for element to be stale (removed from DOM)
await driver.wait(until.stalenessOf(element), 10000);
using OpenQA.Selenium.Support.UI;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be visible (present + displayed)
IWebElement element = wait.Until(
ExpectedConditions.ElementIsVisible(By.Id("content"))
);
// Wait for already-found element to be visible
IWebElement foundElement = driver.FindElement(By.Id("popup"));
wait.Until(d => foundElement.Displayed);
// Wait for all matching elements to be visible
IList<IWebElement> items = wait.Until(
ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("item"))
);
// Wait for element to become invisible
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("loading")));

Clickability Conditions

Waiting for Clickability
Selenium 3 & 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be clickable (visible + enabled)
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(By.id("submit-btn"))
);
button.click();
// Wait for element reference to be clickable
WebElement link = driver.findElement(By.linkText("Continue"));
wait.until(ExpectedConditions.elementToBeClickable(link)).click();
// Pattern: Wait then click
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".action-btn"))).click();
wait = WebDriverWait(driver, 10)
# Wait for element to be clickable (visible + enabled)
button = wait.until(
EC.element_to_be_clickable((By.ID, "submit-btn"))
)
button.click()
# Wait for element reference to be clickable
link = driver.find_element(By.LINK_TEXT, "Continue")
wait.until(EC.element_to_be_clickable(link)).click()
# Pattern: Wait then click
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".action-btn"))).click()
// Wait for element to be enabled
const button = await driver.findElement(By.id('submit-btn'));
await driver.wait(until.elementIsEnabled(button), 10000);
await button.click();
// Combined: locate, wait for clickable, click
const element = await driver.wait(
until.elementLocated(By.id('submit-btn')),
10000
);
await driver.wait(until.elementIsVisible(element), 10000);
await driver.wait(until.elementIsEnabled(element), 10000);
await element.click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be clickable (visible + enabled)
IWebElement button = wait.Until(
ExpectedConditions.ElementToBeClickable(By.Id("submit-btn"))
);
button.Click();
// Wait for element reference to be clickable
IWebElement link = driver.FindElement(By.LinkText("Continue"));
wait.Until(ExpectedConditions.ElementToBeClickable(link)).Click();
// Pattern: Wait then click
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".action-btn"))).Click();

Presence Conditions

Waiting for Element Presence
Selenium 3 & 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be present in DOM (may not be visible)
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(By.id("hidden-data"))
);
// Wait for all matching elements to be present
List<WebElement> elements = wait.until(
ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("item"))
);
System.out.println("Found " + elements.size() + " items");
// Wait for nested element
WebElement parent = driver.findElement(By.id("container"));
WebElement child = wait.until(
ExpectedConditions.presenceOfNestedElementLocatedBy(
parent, By.className("child")
)
);
wait = WebDriverWait(driver, 10)
# Wait for element to be present in DOM (may not be visible)
element = wait.until(
EC.presence_of_element_located((By.ID, "hidden-data"))
)
# Wait for all matching elements to be present
elements = wait.until(
EC.presence_of_all_elements_located((By.CLASS_NAME, "item"))
)
print(f"Found {len(elements)} items")
# Wait for nested element
parent = driver.find_element(By.ID, "container")
child = wait.until(
EC.presence_of_element_located((By.CLASS_NAME, "child"))
)
// Wait for element to be present in DOM
const element = await driver.wait(
until.elementLocated(By.id('hidden-data')),
10000
);
// Wait for multiple elements
const elements = await driver.wait(
until.elementsLocated(By.className('item')),
10000
);
console.log(`Found ${elements.length} items`);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to be present in DOM (may not be visible)
IWebElement element = wait.Until(
ExpectedConditions.ElementExists(By.Id("hidden-data"))
);
// Wait for all matching elements to be present
IList<IWebElement> elements = wait.Until(
ExpectedConditions.PresenceOfAllElementsLocatedBy(By.ClassName("item"))
);
Console.WriteLine($"Found {elements.Count} items");

Text Conditions

Waiting for Text
Selenium 3 & 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to contain specific text
boolean hasText = wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("status"), "Complete"
)
);
// Wait for element's value attribute to contain text
boolean hasValue = wait.until(
ExpectedConditions.textToBePresentInElementValue(
By.id("result"), "Success"
)
);
// Wait for exact text match
WebElement element = driver.findElement(By.id("message"));
wait.until(ExpectedConditions.textToBe(By.id("message"), "Done!"));
wait = WebDriverWait(driver, 10)
# Wait for element to contain specific text
has_text = wait.until(
EC.text_to_be_present_in_element(
(By.ID, "status"), "Complete"
)
)
# Wait for element's value attribute to contain text
has_value = wait.until(
EC.text_to_be_present_in_element_value(
(By.ID, "result"), "Success"
)
)
# Wait for exact text match
# (use a custom condition or text_to_be_present_in_element)
// Custom text condition
async function textToBe(locator, expectedText) {
return async (driver) => {
try {
const element = await driver.findElement(locator);
const text = await element.getText();
return text === expectedText;
} catch (e) {
return false;
}
};
}
// Wait for text
await driver.wait(textToBe(By.id('status'), 'Complete'), 10000);
// Wait for text to contain
await driver.wait(async () => {
const el = await driver.findElement(By.id('status'));
const text = await el.getText();
return text.includes('Complete');
}, 10000);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for element to contain specific text
bool hasText = wait.Until(
ExpectedConditions.TextToBePresentInElementLocated(
By.Id("status"), "Complete"
)
);
// Wait for element's value attribute to contain text
bool hasValue = wait.Until(
ExpectedConditions.TextToBePresentInElementValue(
By.Id("result"), "Success"
)
);

Frame and Window Conditions

Frame and Window Waits
Selenium 3 & 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for frame to be available and switch to it
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("myframe")));
// Now interacting with frame content
// Switch back to main content
driver.switchTo().defaultContent();
// Wait for frame by name or index
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frameName"));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(0)); // First frame
// Wait for new window/tab
String mainWindow = driver.getWindowHandle();
driver.findElement(By.id("open-new-window")).click();
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
break;
}
}
wait = WebDriverWait(driver, 10)
# Wait for frame to be available and switch to it
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "myframe")))
# Now interacting with frame content
# Switch back to main content
driver.switch_to.default_content()
# Wait for frame by name or index
wait.until(EC.frame_to_be_available_and_switch_to_it("frameName"))
wait.until(EC.frame_to_be_available_and_switch_to_it(0)) # First frame
# Wait for new window/tab
main_window = driver.current_window_handle
driver.find_element(By.ID, "open-new-window").click()
wait.until(EC.number_of_windows_to_be(2))
for handle in driver.window_handles:
if handle != main_window:
driver.switch_to.window(handle)
break
// Wait for frame and switch
const frame = await driver.wait(
until.ableToSwitchToFrame(By.id('myframe')),
10000
);
// Switch back to main content
await driver.switchTo().defaultContent();
// Wait for new window
const mainWindow = await driver.getWindowHandle();
await driver.findElement(By.id('open-new-window')).click();
await driver.wait(async () => {
const handles = await driver.getAllWindowHandles();
return handles.length === 2;
}, 10000);
const handles = await driver.getAllWindowHandles();
const newWindow = handles.find(h => h !== mainWindow);
await driver.switchTo().window(newWindow);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for frame to be available and switch to it
wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.Id("myframe")));
// Now interacting with frame content
// Switch back to main content
driver.SwitchTo().DefaultContent();
// Wait for new window/tab
string mainWindow = driver.CurrentWindowHandle;
driver.FindElement(By.Id("open-new-window")).Click();
wait.Until(d => d.WindowHandles.Count == 2);
foreach (string handle in driver.WindowHandles)
{
if (handle != mainWindow)
{
driver.SwitchTo().Window(handle);
break;
}
}

Alert Conditions

Waiting for Alerts
Selenium 3 & 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for alert to appear
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// Get alert text
String alertText = alert.getText();
System.out.println("Alert says: " + alertText);
// Accept (OK) the alert
alert.accept();
// Or dismiss (Cancel) the alert
// alert.dismiss();
// Handle prompt (alert with input)
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("My input");
prompt.accept();
wait = WebDriverWait(driver, 10)
# Wait for alert to appear
alert = wait.until(EC.alert_is_present())
# Get alert text
alert_text = alert.text
print(f"Alert says: {alert_text}")
# Accept (OK) the alert
alert.accept()
# Or dismiss (Cancel) the alert
# alert.dismiss()
# Handle prompt (alert with input)
prompt = wait.until(EC.alert_is_present())
prompt.send_keys("My input")
prompt.accept()
// Wait for alert to appear
await driver.wait(until.alertIsPresent(), 10000);
const alert = await driver.switchTo().alert();
// Get alert text
const alertText = await alert.getText();
console.log(`Alert says: ${alertText}`);
// Accept (OK) the alert
await alert.accept();
// Or dismiss (Cancel)
// await alert.dismiss();
// Handle prompt
const prompt = await driver.switchTo().alert();
await prompt.sendKeys('My input');
await prompt.accept();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
// Wait for alert to appear
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
// Get alert text
string alertText = alert.Text;
Console.WriteLine($"Alert says: {alertText}");
// Accept (OK) the alert
alert.Accept();
// Or dismiss (Cancel) the alert
// alert.Dismiss();
// Handle prompt (alert with input)
IAlert prompt = wait.Until(ExpectedConditions.AlertIsPresent());
prompt.SendKeys("My input");
prompt.Accept();

Expected Conditions Reference

ConditionWaits For
visibilityOfElementLocatedElement visible on page
invisibilityOfElementLocatedElement not visible
elementToBeClickableElement visible and enabled
presenceOfElementLocatedElement in DOM
textToBePresentInElementElement contains text
alertIsPresentJavaScript alert appears
frameToBeAvailableAndSwitchToItFrame loads and switches
numberOfWindowsToBeSpecific window count
stalenessOfElement removed from DOM
attributeToBeAttribute has value
urlContainsURL contains text
titleContainsPage title contains text

Java: ExpectedCondition No Longer Uses Guava (4.51+)

Since Selenium 4.51 the Java client no longer depends on Guava, and ExpectedCondition<T> extends only java.util.function.Function<WebDriver, T>. Before that it also extended Guava’s com.google.common.base.Function.

Most code is unaffected. Passing ExpectedConditions.* or a lambda to wait.until(...) compiles exactly as before. What breaks:

  • Variables, fields or method signatures typed as com.google.common.base.Function that hold an ExpectedCondition.
  • Helpers that call Guava-only methods on a condition, or chain it with Guava’s Functions / Predicates utilities.
  • Code that used Guava classes (ImmutableList, Lists, Preconditions) without declaring Guava, because it used to arrive transitively through Selenium.

The fix is mechanical:

// Before (fails to compile on 4.51+)
import com.google.common.base.Function;
Function<WebDriver, WebElement> ready = ExpectedConditions.elementToBeClickable(By.id("save"));
// After: use ExpectedCondition, or the JDK Function
import org.openqa.selenium.support.ui.ExpectedCondition;
ExpectedCondition<WebElement> ready = ExpectedConditions.elementToBeClickable(By.id("save"));

If you still use Guava elsewhere in the project, declare it as an explicit dependency instead of relying on Selenium to bring it in. Python, JavaScript and C# are not affected.

Note: Search your Java test code for import com.google.common.base.Function before upgrading to 4.51. It is the one import that turns a routine version bump into a compile failure.

Next Steps

Finished this lesson?

Mark it complete to track your progress through the course. Saved in this browser only.

Test yourself Waits & Synchronization 10 questions · intermediate Fix a broken test Replace Every Sleep with a Real Wait beginner · 15 min

Copy-paste recipes

Errors you may hit

  • ElementClickInterceptedException

    Fix Selenium ElementClickInterceptedException (ElementClickInterceptedError in JS): overlays, cookie banners, sticky headers and animations blocking your click.

  • ElementNotInteractableException

    Fix Selenium ElementNotInteractableException (ElementNotInteractableError in JS): hidden elements, duplicate matches, zero-size inputs and custom controls.

  • NoSuchFrameException

    Fix Selenium NoSuchFrameException (NoSuchFrameError in JS): iframes that load late, wrong frame names or indexes, nested frames and re-rendered iframes.

  • NoSuchWindowException

    Fix Selenium NoSuchWindowException (NoSuchWindowError in JS): closed tabs, self-closing popups, stale window handles and switching before a new tab opens.

Related lessons