Difference between findElement and findElements method in Selenium with Java

Profile picture for user ksharma

findElement and findElements methods are used to find the elements on a webpage. Below are the difference between both:

Point of DistinctionfindElementfindElements
UseA command used to uniquely identify a web element within the web page.Used to identify a list of web elements within the web page.
ReturnsIt returns the first matching element.returns the list of all matching elements. Each Web element is indexed with a number starting from 0 just like an array
NoSuchElementExceptionIt throws a NoSuchElementException exception when it fails to find the element.the findElements method returns  an empty list when the element is not available or doesn’t exist on the page. It doesn’t throw NoSuchElementException.
Syntaxdriver.findElement(By.locatorType("Locators Value"));driver.findElements(By.locatorType("Locator Value"));

Example 

package com.pb.seltest.util;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class DiffFindElements 
{
    WebDriver driver;
	
    @BeforeClass
    public void befClass()
    {
        System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.get("http://www.automationpractice.com");
    }
	
    @Test
    public void MyMethod()
    {
        System.out.println("findElement Output");
        WebElement element = driver.findElement(By.xpath("//div[@id='block_top_menu']/ul/li/a"));
        System.out.println(element.getText());
		
        System.out.println("findElements Output");
        List<WebElement> allMenus = driver.findElements(By.xpath("//div[@id='block_top_menu']/ul/li/a"));
		
        for(int i = 0; i < allMenus.size(); i++)
            System.out.println(allMenus.get(i).getText());
    }	
}

Output:

findElement Output
WOMEN
findElements Output
WOMEN
DRESSES
T-SHIRTS
PASSED: MyMethod

In above example, we are finding menu links for automationpractice.com. We have used same locators here, but different methods which are findElement and findElements. findElement will only retrieve first link with Name Women and findElements will retrieve all the menu links Women, dresses and t-shirts.

For findElement we are storing result in WebElement because it is returning single result. For findElements we have used List of WebElements because it is returning list of elements.