| Feature | findElement() | findElements() |
|---|---|---|
| Returns | Single WebElement | List<WebElement> |
| If not found | Throws NoSuchElementException | Returns empty list |
| Multiple matches | Returns first match only | Returns all matches |
| Use case | Unique elements | Lists, tables, repeated items |
findElement():
Java
WebElement btn = driver.findElement(By.cssSelector(".submit-btn"));
btn.click();
// Throws NoSuchElementException if not found
findElements():
Java
List<WebElement> items = driver.findElements(By.cssSelector(".product-item"));
System.out.println("Count: " + items.size());
for (WebElement item : items) {
System.out.println(item.getText());
}
Check element exists without exception:
Java
List<WebElement> elements = driver.findElements(By.id("loginBtn"));
if (!elements.isEmpty()) {
elements.get(0).click();
}
Get row count of a table:
Java
int rowCount = driver.findElements(By.tagName("tr")).size();
System.out.println("Table rows: " + rowCount);
