</>

Technology

Selenium

Difficulty

Beginner

Interview Question

What is the difference between driver.findElement() and driver.findElements() commands?

findElement() returns the first matching WebElement or throws NoSuchElementException; findElements() returns a List of all matches or an empty list.

Answer

findElement() — returns the first matching element:

Java
WebElement textbox = driver.findElement(By.id("textBoxLocator"));

Throws NoSuchElementException if no element matches.

findElements() — returns all matching elements as a List:

Java
List<WebElement> elements = driver.findElements(By.id("value"));

Returns an empty List (size 0) if no elements match — never throws.

Full comparison:

FeaturefindElement()findElements()
Return typeWebElementList<WebElement>
If not foundThrows NoSuchElementExceptionReturns empty list
Multiple matchesReturns FIRST matchReturns ALL matches
Use caseUnique elementsTables, lists, repeated items

Use findElements() to safely check if element exists:

Java
List<WebElement> list = driver.findElements(By.id("loginBtn"));
if (!list.isEmpty()) {
    list.get(0).click();
}

Count elements on page:

Java
int count = driver.findElements(By.cssSelector(".product-card")).size();
System.out.println("Products found: " + count);

Follow AutomateQA

Related Topics