How to find a JavaScript-generated element with Selenium WebDriver?

I’m having trouble locating an element created by JavaScript using Selenium WebDriver in Java. I’ve tried using WebDriverWait and even Thread.sleep, but no luck.

Here’s what I’m trying to do:

  1. Click a button that triggers JavaScript to create a div
  2. Use Selenium to find and interact with that div

I’ve attempted various locator strategies like:

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("new-div-id")));
driver.findElement(By.id("new-div-id")).click();

I’ve also tried XPath, CSS selectors, and class names. Nothing works! The WebDriver always times out.

My wait is set up like this:

WebDriverWait wait = new WebDriverWait(driver, 100);

Am I missing something obvious? How can I make Selenium find this JavaScript-created element? Any tips or tricks would be super helpful!

I’ve encountered similar issues with dynamically generated elements. One approach that’s worked well for me is using a custom ExpectedCondition. Here’s an example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(new ExpectedCondition() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
“return document.getElementById(‘new-div-id’) != null”);
}
});

This waits for the element to exist in the DOM before attempting to interact with it. It’s more reliable than visibility checks for JavaScript-created elements. Once the condition is met, you can safely use findElement to locate and interact with the div.

hey, have you tried using javascriptexecutor to check if the element exists? sometimes selenium struggles with dynamic content. you could do something like:

driver.executeScript(“return document.getElementById(‘new-div-id’) !== null”);

if that returns true, then use your normal findElement. might help catch timing issues.

I’ve dealt with this exact problem before, and it can be frustrating. One thing that worked for me was using a custom FluentWait instead of WebDriverWait. It gives you more control over the polling frequency and exceptions to ignore. Here’s a snippet that might help:

WebElement element = new FluentWait(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class)
.until(ExpectedConditions.presenceOfElementLocated(By.id(“new-div-id”)));

element.click();

This approach keeps trying to find the element for up to 30 seconds, checking every 500ms. It also ignores NoSuchElementException, which is common when dealing with dynamic content. Give it a shot and see if it helps with your timing issues.