We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Target specific conditions with WebDriverWait for dynamic UI elements
Explicit waits are targeted waits that poll until a specific condition is true or timeout occurs.
Unlike implicit waits (which apply globally), explicit waits give you precise control over:
Creates a targeted wait that polls until a condition is true or timeout occurs.
Waits up to 5 seconds for element to be visible
Imagine a page called "Dynamic Content Playground" with delayed elements:
Box will appear 2 seconds after clicking the button
Input will appear 2 seconds after clicking the button
Nothing done yet.
Interact with the buttons to see delayed elements appear, simulating dynamic content!
Displayed via waits.Your Selenium code will use WebDriverWait + ExpectedConditions to wait for the box to exist and the input to be visible.
12345678910111213141516171819202122WebElement addBoxButton = driver.findElement(By.id("add-box-btn"));
WebElement revealInputButton = driver.findElement(By.id("reveal-input-btn"));
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
// 1. Click "Add a box!" and wait for the new box to exist in the DOM
addBoxButton.click();
WebElement dynamicBox = wait.until(
ExpectedConditions.presenceOfElementLocated(By.id("dynamic-box"))
);
// 2. Click "Reveal a new input" and wait until the input is visible
revealInputButton.click();
WebElement revealedInput = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("revealed-input"))
);
// 3. Type into the revealed input
revealedInput.clear();
revealedInput.sendKeys("Displayed via waits");
driver.quit();id="add-box-btn".<div> with id="dynamic-box" exists in the DOM (even if it's not visible yet). Returns the element once it appears. Polls every 500ms until found or 5s timeout.id="revealed-input" is present AND visible before proceeding. Note: visibilityOf is stricter than presenceOf—the element must have height/width and not be hidden."Displayed via waits" into the now-visible input. This updates the status text on the page.Use explicit waits + ExpectedConditions for dynamic elements instead of Thread.sleep(...) – your tests become faster and more reliable.
Avoid mixing large implicit waits with explicit waits; rely mainly on explicit waits where needed. Combining them can lead to unexpected cumulative timeouts.
Create one WebDriverWait instance and reuse it for multiple conditions. This keeps your code clean and reduces object creation overhead.