Careeroza
findElement vs findElements
The Difference
findElement | findElements | |
|---|---|---|
| Returns | one WebElement (the first match) | List<WebElement> (all matches) |
| No match | throws NoSuchElementException | returns an empty list (size 0) |
| Use for | a button, a text box | product cards, rows, links, "is it present?" checks |
When Nothing Matches
driver.findElement(By.id("login")); // the real id is login-btnExample
Selenium throws:
Run LocatorTest.main()Example output
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#login"}
(Session info: chrome=130.0.6723.70)
For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exceptionNote: Selenium 4 converts By.id("login") into the CSS selector #login internally, so the message says "css selector".
Checking Presence Safely
boolean errorShown = !driver.findElements(By.cssSelector(".error-message")).isEmpty();
System.out.println("Error visible: " + errorShown);
List<WebElement> cards = driver.findElements(By.cssSelector(".product-card"));
for (WebElement card : cards) {
System.out.println(card.findElement(By.tagName("h3")).getText()); // search inside one card
}Example
Output:
Run SearchResults.main()Example output
Error visible: false Nike Revolution 7 Puma Velocity Nitro Adidas Duramo SL
Tip: element.findElement(...) searches only inside that element. Use it to read the name and price of each product card.