Difference between findElement and findElements with example in selenium WebDriver


In this tutorial, I would like to explain differences between findElement and findElements with examples.WebDriver gives findElement and findElements methods to locate elements on a web page.

1. findElement

  • It finds the first WebElement using the given input
  • It can access single element on a page.
  • It throws NoSuchElementException, when element is not available on the page as per the given element locator mechanism.

Example :

package com.selenium.practise;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindElement {

	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "E:\\Soft Wares\\chromedriver.exe");	
		WebDriver driver = new ChromeDriver();
		driver.get("https://www.google.com/");
		WebElement list=driver.findElement(By.name("q"));
		list.sendKeys("Today");
		System.out.println("Example of findElement is completed");
		driver.close();
	}

}

2. findElements

  • It finds all elements within the current page using the given input.
  • It returns list of the all matching elements from current page.
  • It returns empty list, when element is not found on current page as per the given element locator mechanism. It doesn't throws NoSuchElementException

Example :

package com.selenium.practise;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindElements {

	public static void main(String[] args) {
		
		System.setProperty("webdriver.chrome.driver", "E:\\Soft Wares\\chromedriver.exe");
		
		WebDriver driver = new ChromeDriver();
		
		driver.get("https://www.google.com/");
        
		List<WebElement> list = driver.findElements(By.tagName("input"));
		System.out.println(list.size());
		for (int i=0;i<list.size();i++){
			String name= list.get(i).getAttribute("name"); 
		    if(name.equals("q")){
		        list.get(i).sendKeys("today");
		        break;  
		    }
		}
	System.out.println("Example of findElements is completed");
	driver.close();
	}

}