</>

Technology

Selenium

Difficulty

Beginner

Interview Question

What is the difference between findElement() and findElements() in Selenium?

findElement() returns a single WebElement and throws NoSuchElementException if not found; findElements() returns a List that is empty if nothing matches.

Answer

FeaturefindElement()findElements()
ReturnsSingle WebElementList<WebElement>
If not foundThrows NoSuchElementExceptionReturns empty list
Multiple matchesReturns first match onlyReturns all matches
Use caseUnique elementsLists, 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);

Follow AutomateQA

Related Topics