We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Use findElements to work with 0..N elements safely and loop over them.
In real web apps, you often have multiple elements that share the same locator:
Selenium gives you two different methods:
findElement(...) – singularNoSuchElementException if nothing matches.findElements(...) – pluralnull and not an exception.findElement → "Give me one element or fail."findElements → "Give me all elements, or an empty list if none."Lets you:
It's the standard way to handle 0..N elements in Selenium.
findElements whenever you are not 100% sure the elements will be present..isEmpty() on lists when you want to safely test presence/absence.In this practice, you will work with a row of filter buttons that all share the same class.
Active filters: None
Click the filter buttons directly to see them toggle. Use Selenium's findElements to interact with all buttons!
class="lesson6-filter-btn"class="warning-msg"findElements to:.lesson6-filter-btn."Java".findElements again to safely check if any .warning-msg elements exist.12345678910111213141516List<WebElement> filters = driver.findElements(By.cssSelector(".lesson6-filter-btn"));
for (WebElement filter : filters) {
String text = filter.getText().trim();
if ("Java".equals(text)) {
filter.click();
break;
}
}
List<WebElement> warnings = driver.findElements(By.cssSelector(".warning-msg"));
if (warnings.isEmpty()) {
System.out.println("No warnings found (Safe check)");
}
driver.quit();findElements (plural) to get all buttons with class lesson6-filter-btn. If none exist, filters will be an empty list, not null."Java". If yes, we click it and then break to stop the loop (no need to continue).findElements call to search for any warning messages on the page. Again, this returns an empty list if nothing matches..isEmpty() to do a safe presence check. No exceptions, regardless of whether warnings exist or not.It's better to check .isEmpty() on a list than to catch NoSuchElementException from findElement.
Get the list once, then loop and decide what to do inside the loop (click, assert, collect data).
When searching by text, always normalize (e.g., .trim()) so small formatting changes don't break your tests.