0
0
Selenium Javatesting~5 mins

findElements for multiple matches in Selenium Java

Choose your learning style9 modes available
Introduction

We use findElements to get all web elements that match a locator. This helps when we want to work with many items on a page, not just one.

You want to check all buttons with the same class on a page.
You need to count how many links are in a menu.
You want to click each checkbox in a list.
You want to verify all error messages shown on a form.
You want to collect text from multiple similar elements.
Syntax
Selenium Java
List<WebElement> elements = driver.findElements(By.locatorType("locatorValue"));

findElements returns a list of elements, even if none are found (empty list).

Use By to specify how to find elements (id, className, xpath, cssSelector, etc.).

Examples
Finds all elements with class btn.
Selenium Java
List<WebElement> buttons = driver.findElements(By.className("btn"));
Finds all anchor (a) tags on the page.
Selenium Java
List<WebElement> links = driver.findElements(By.tagName("a"));
Finds all list items inside unordered lists.
Selenium Java
List<WebElement> items = driver.findElements(By.xpath("//ul/li"));
Sample Program

This program opens a webpage, finds all buttons with class btn, prints how many it found, and prints each button's text.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;

public class FindElementsExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/samplepage");

            // Find all buttons with class 'btn'
            List<WebElement> buttons = driver.findElements(By.className("btn"));

            System.out.println("Number of buttons found: " + buttons.size());

            // Print text of each button
            for (WebElement button : buttons) {
                System.out.println("Button text: " + button.getText());
            }
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

If no elements match, findElements returns an empty list, not an error.

Always quit the driver to close the browser after the test.

Use meaningful locators to avoid finding wrong elements.

Summary

findElements gets all matching elements as a list.

It helps when you want to work with many similar elements.

Returns empty list if no matches, so no crash.