Dynamic Lists and Auto Suggest

Auto-suggest Search

Typing "iph" in the ShopEase search box shows a list of suggestions that loads after a short delay. Wait for the suggestions, then click the one you want by text.

<ul class="suggestions">
  <li>iphone 15</li>
  <li>iphone 15 cover</li>
  <li>iphone charger</li>
</ul>

Selecting a Suggestion

driver.findElement(By.id("search")).sendKeys("iph");
List<WebElement> items = wait.until(
        ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(".suggestions li")));
System.out.println("Suggestions: " + items.size());
for (WebElement item : items) {
    if (item.getText().equalsIgnoreCase("iphone 15 cover")) {
        item.click();
        break;
    }
}
wait.until(ExpectedConditions.urlContains("q=iphone+15+cover"));

Example

Output:

Run AutoSuggestTest.main()

Example output

Suggestions: 3

StaleElementReferenceException

If the list re-renders while you loop (each keystroke rebuilds it), elements you found earlier are gone from the DOM:

Example

Run AutoSuggestTest.main()

Example output

org.openqa.selenium.StaleElementReferenceException: stale element reference: stale element not found in the current frame

Tip: Finish typing, wait for the final list, then find the elements again. Do not keep old WebElement references after the page changes.