Heuristic:SeleniumHQ Selenium FindElements For Absence Check
| Knowledge Sources | |
|---|---|
| Domains | Testing, Best_Practices, Element_Location |
| Last Updated | 2026-02-11 23:00 GMT |
Overview
Use `findElements()` with zero-length assertion instead of `findElement()` when checking that an element does not exist on the page.
Description
The `findElement()` method throws a `NoSuchElementException` when no matching element is found, forcing try/catch exception handling for absence checks. This is both slower (exception creation is expensive) and less readable. The `findElements()` method returns an empty list instead of throwing, allowing a simple assertion on list size. Both the WebDriver and WebElement Javadocs explicitly recommend this pattern.
Usage
Apply this heuristic in any test assertion that verifies an element has been removed, hidden, or was never rendered. It is especially important when combined with implicit waits, where `findElement()` will wait the full timeout before throwing, while `findElements()` returns immediately with an empty list if no match is found.
The Insight (Rule of Thumb)
- Action: Replace `findElement()` with `findElements()` for non-presence assertions.
- Value: Returns empty list immediately instead of waiting and throwing exceptions.
- Trade-off: None; strictly better for absence checks.
- Pattern: `assertThat(driver.findElements(By.id("removed"))).isEmpty()`
Reasoning
The WebDriver Javadoc explicitly states this guidance: "findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead." This appears in both `WebDriver.java` and `WebElement.java`, indicating it is a deliberate design recommendation. Exception-based control flow is a well-known anti-pattern; `findElements()` avoids this by using return values for flow control.
Code Evidence
WebDriver Javadoc guidance from `java/src/org/openqa/selenium/WebDriver.java:114-115`:
// "findElement should not be used to look for non-present elements, use
// #findElements(By) and assert zero length response instead."
WebElement Javadoc guidance from `java/src/org/openqa/selenium/WebElement.java:254-255`:
// "findElement should not be used to look for non-present elements, use
// #findElements(By) and assert zero length response instead."