Q7 of 37 · Selenium
What is the difference between findElement and findElements?
Short answer
Short answer: findElement returns a single WebElement and throws NoSuchElementException if nothing matches. findElements returns a list — empty if no matches, never throws. Use the plural when existence is uncertain.
Detail
Both look at the current DOM and apply the locator, but they handle the zero-match case differently — and that difference is the whole point.
findElement(By) returns a single WebElement. If nothing matches, it throws NoSuchElementException. If multiple match, it returns the first one in document order. Use it when:
- The element is required for the test to continue (
Submitbutton on the login page). - You want a fast failure with a clear stack trace.
findElements(By) returns a List<WebElement>. If nothing matches, the list is empty (no exception). Use it when:
- You're checking whether something is present (
isErrorVisible-style). - You're iterating over multiple matching elements (rows, search results).
- You need to gracefully handle the "zero matches" case as a valid outcome.
A subtle gotcha: neither method waits by default. If you call findElements immediately after a click, you may get an empty list because the element hasn't appeared yet. Wrap in an explicit wait if timing matters:
new WebDriverWait(driver, Duration.ofSeconds(5))
.until(d -> !d.findElements(By.cssSelector(".error")).isEmpty());
Choose intentionally: findElement for "should exist," findElements for "may exist."