Table of Contents

A webpage consists of numerous WebElements such as text boxes, buttons, lists, etc. Selenium allows us to perform a variety of actions on these WebElements using different WebDriver commands. However, to perform these actions, we must be able to target the exact element on the page. For this, we need to rely on multiple strategies, which are collectively available in the findElement and findElements methods of Selenium. This article is meant to dive deep into it, as it is one of the most common operations performed in Selenium.

Overview of the article:

  • Find elements using Selenium WebDriver?
  • Why do we need to find a web element in Selenium?
  • How to find elements in Selenium?
  • What is By class in Selenium?
  • Difference between findElement and findElements in Selenium.

Find elements using Selenium WebDriver

To interact with WebElements on a web page, we first have to find or locate these elements on the page. There are multiple locators that we use for element identification so the driver can attach its action to the correct element. Using these locators is called locator strategies.. These locators serve as the inner part of the findElement and findElements functions in Selenium.

selenium_locators_table.png

Selenium uses two methods along with these locator strategies to find elements:

  • findElement: Method to uniquely identify a web element within the web page.
  • findElements: Method to identify a list of web elements within the web page.

In the next sections, the syntax and demo examples will make their usage clearer.

Why do we need to find an element in Selenium?

findElement and locator strategies in Selenium help identify elements on a web page. It's a process by which we find elements. But as a Selenium automation tester, why do we need to do that? What are the benefits we reap when we implement findElement and findElements in our test cases? The most important ones are as follows:

  • Identifying Elements: As described before, findElement and findElements help identify the elements on a web page.
  • Enable User Interaction: These methods enable a tester to perform actions similar to how a user would interact with the elements on the page. This gives a better picture of user experience and fewer surprises for the end user post-production.
  • Fewer Flaky Tests: Both these methods will always identify the correct elements as described by the locator. Hence, tests become more reliable, and the suites are more stable.
  • Dynamic Page Handling: Dynamic pages are common on websites, and the elements in such pages change quickly. findElement and findElements provide a reliable way to always target the correct element even though the code of the page has changed.
  • Validation: findElement and findElements catch the target elements and provide their characteristics such as attributes, state, visibility, etc. It serves an integral part in validation and assertions to make sure the behavior of elements is as expected.

Here we would like to advice to use our playground website "demoqa.com" for practicing purposes.

demoqa.com example website

In this article, it will be used for demonstrations.

How to find elements in Selenium?

As discussed, Selenium WebDriver provides two methods using which we can find an element or list of elements on a web page. These are:

findElement(): This method uniquely finds a web element on the web page.

findElements(): This method finds a list of web elements on the web page.

Let's understand the usage and details of these methods in the following sections:

How To Use findElement() In Selenium

The findElement() method of the Selenium WebDriver finds a unique web element within the webpage.

Syntax of the findElement command in Selenium WebDriver:

WebElement elementName = driver.findElement
                  (By.LocatorStrategy("LocatorValue"));

As shown in the above syntax, this command accepts the "By " locator as the argument and returns a WebElement object.

The "By" is a locator or query object and accepts the locator specifiers or strategies we discussed above. You can use multiple strategies here depending on the requirement. These are listed below:

selenium_by_strategies_table.png

The above screenshot shows all the options that we get when we write 'By'. We will explain each of these strategies in the later sections of this chapter.

Note: In case there is no matching element found, the findElement command throws NoSuchElementException. However, if multiple elements match up, the findElement() method returns the first matched element within the web page.

How To Use findElements() in Selenium

The command findElements() returns a list of web elements that match the specified criteria, unlike findElement() which returns a unique element. If there are no matching elements, then an empty list is returned.

Syntax of findElements() command in Selenium WebDriver:

List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

Similar to the findElement() command, the findElements() method also accepts the "By " object as the parameter and returns a WebElement list.

Let us consider an example wherein we need to find the number of elements having tag name as "input " on the DemoQA text box page. The inspect panel for this is as below.

demoqa.com to find elements

In the above screenshot, when we search for the tag name 'input', two entries return (shown by the red rectangle around the search tool which says 1/2).

The following program shows an example of the findElements() method in Selenium, where we provide the By object with tagName.

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 FindElementByTagName {
   public static void main(String[] args) {
	   System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		

	   WebDriver driver = new ChromeDriver();

	   driver.get("https://demoqa.com/text-box/");
		
	   // Find elements using tag name
	   List<WebElement> allInputElements = driver.findElements(By.tagName("input"));
		
	   if(allInputElements.size() != 0) 
	   {
		   System.out.println(allInputElements.size() + " Elements found by TagName as input \n");
			
		   for(WebElement inputElement : allInputElements) 
		   {
			   System.out.println(inputElement.getAttribute("placeholder"));
		   }
	   }
   }
}

Output:

findElements program output

Next, let's understand how to use different locator strategies with findElement() and findElements() commands.

How to use findElement() with "id" in Selenium?

Using "id" to find an element is the most common strategy used to find an element because most of the elements use ID as a locator on a web page. findElement targets the "ID" attribute of the web element and returns the first matched ID if there are multiple of them.

Syntax of findElement() command with By id strategy:

WebElement elm = driver.findElement(By.id("Element_Id"));

As an example consider the following element in the DemoQA text box page:

find an element in Selenium by Id

Here we have selected the "submit " button (marked 1). The element code for this is marked 2 in the above screenshot.

The findElement() command corresponding to the above element:

WebElement element = driver.findElement(By.id("submit"));
// Action can be performed on the button element
element.submit();

Note: If none of the web elements within the web page matches the id attribute, then a "NoSuchElementException" is raised.

The complete program to find an element using the "By.id " object with findElement() in Selenium is as seen below:

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

public class FindElementById {

     public static void main(String[] args) {
		
	System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		
		
	WebDriver driver = new ChromeDriver();
		
	driver.get("https://demoqa.com/text-box/");
        WebElement element = driver.findElement(By.id("submit"));
		
		
	if(element != null) {
	    System.out.println("Element found by ID");
	}
   }
}

This program gives the following output.

Program Output By Id

The above program is a program to find an element using the ID (By.Id) of that element. We provide an appropriate URL from which we need to search for an element and then call "findElement()" with the argument By.id("elementID"). This call returns the given element with the specified ID.

How to use findElement() with "name" in Selenium?

Finding an element in Selenium using findElement with name is the same as id except that the locator locates an element using the "name" attribute instead of "id ".

The value of the name attribute accepted is of type String. The general syntax of the findElement() method with the By.name strategy is as follows.

WebElement elm = driver.findElement(By.name("Element_NAME"));

As an example, consider the following element on the page DemoQAAutomationPracticeForm :

find an element in Selenium by Name

In the above screenshot, we select the first gender value (marked 1). Its corresponding element in the DOM  is highlighted (marked 2).

The corresponding findElement() method call for the above element is:

WebElement element = driver.findElement(By.name("gender"));
// Action can be performed on Input Text element
element.sendKeys("ToolsQA");

As a result of this method call, the first element matching the given name attribute value is returned. If we can not find a match, NoSuchElementException is raised.

Consider the following element:

find an element in Selenium by Name more than one entries

In the above screenshot, there are two elements with the same name =  gender. In this case, the findElement() method returns the first element.

The following code shows the program to find an element using Name (By.name):

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

public class FindElementByName {
     public static void main(String[] args) {
	   System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		
      	   WebDriver driver = new ChromeDriver();

	   driver.get("https://demoqa.com/automation-practice-form");
		
	   WebElement element = driver.findElement (By.name("gender"));
	   if(element != null) {
	 	System.out.println("Element found by Name");
	   }
	}
}

The program gives the following output.

Program Output By name

The above program finds an element in Selenium using the name. We provide the name of the element that we can use to search as an argument to the By object in the 'findElement()' call.

How to use findElement() with className in Selenium?

To locate an element by its class name, pass the value of its "class" attribute as the locator. This approach works well when you want to target elements that share the same CSS class.

This locator strategy accepts a parameter of type String. The general syntax with the className strategy:

List<WebElement> webList = driver.findElements(By.className(<Element_CLASSNAME>)) ;

or

WebElement elm = driver.findElement(By.className(<Element_CLASSNAME>)) ;

The first syntax returns a list of matching elements by class name, while the second returns only one matching element.

If an element has multiple classes, this strategy matches each class.

Consider the following element (submit button) on DemoQAAutomationPracticeForm :

find an element in Selenium by className

The corresponding command for finding the element marked above is:

WebElement parentElement = driver.findElement(By.className("button"));
parentElement.submit();

*Note: The findElement method in Selenium with the Class Name locator strategy is useful when an element doesn't have a unique ID or name. In such cases, we can locate the element by its class attribute instead. When using By.className(), Selenium searches the DOM for elements whose class attribute contains the specified class name and returns the first matching element.

The program to find an element using By.className is as below:

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

public class FindElementByClassName {
	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		

		WebDriver driver = new ChromeDriver();

		driver.get("https://demoqa.com/automation-practice-form");
		
		WebElement parentElement = driver.findElement (By.className("button"));
		
		if(parentElement != null) {
			System.out.println("Element found by ClassName");
		}
		
	}
}

This program gives the following output.

Program Output By className

In this program, we have provided a class name "button" as a By object argument in the 'findElement()' call. It scans the page and returns an element with className = "button".

How to use findElement() with HTML tagName in Selenium?

The Tag Name strategy, when used with findElement, finds elements by their HTML tag, such as input, button, or a (an anchor tag). It's rarely used, mostly as a last resort when no other locator strategy can identify the element.

The value of the TAG attribute is a String type parameter. The syntax of the findElement() method using this strategy:

WebElement elem =&nbsp; driver.findElement(By.tagName(“Element_TAGNAME”));

As an example, consider the following element on DemoQAAutomationPracticeForm :

find an element in Selenium by tagName

The corresponding command for the above element (input tag) is as follows:

WebElement element = driver.findElement(By.tagName("input"));

The following is the program to find elements using By.tagName object.

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 FindElementByTagName {

     public static void main(String[] args) {
	  System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		

	  WebDriver driver = new ChromeDriver();
          driver.get("https://demoqa.com/automation-practice-form");
	  WebElement element = driver.findElement (By.tagName("input"));
	  if(element != null) {
	       System.out.println("Element found by tagName");
	  }
     }
}

The output of this program is as seen below.

Program Output By tagName

The above program uses the By.tagName object in the 'findElement()' call to find an element based on tagName = "input".

How to use findElement() with "CSS Selector" in Selenium?

We can also use the CSS Selector strategy as an argument to By when finding the element. Since CSS Selector has native browser support, sometimes the CSS Selector strategy is faster than the XPath strategy.

Again, we will choose an element from the page DemoQAAutomationPracticeForm :

find an element in Selenium by CSS selector

The CSS Selector for the above input field is #firstName. So the corresponding command to findElement by CSS Selector in Selenium is:

WebElement inputElem = driver.findElement(By.cssSelector("input[id = 'firstName']"));
inputElem.SendKeys("demoQA");

The following program shows how to find elements using the By.cssSelector construct.

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

public class FindElementByCssSelector {
	public static void main(String[] args) {
	     System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		
    	     WebDriver driver = new ChromeDriver();
             driver.get("https://demoqa.com/automation-practice-form");
	     WebElement inputElem = driver.findElement (By.cssSelector("input[id = 'firstName']"));
	     if(inputElem != null) {
		 System.out.println("Element found by cssSelector");
	     }
	}
}

The program gives the following output.

Program Output By cssSelector

The above program finds an element using a CSS Selector for the field 'firstNam' by using the By.cssSelector locator strategy. The program returns an element having the specified CSS selector.

How to use findElement() with XPath in Selenium?

Working with findElement() method along with XPath is one of the most popular strategy for finding elements on a web page. Using this strategy, we navigate through the structure of the HTML or XML documents.

This strategy accepts a String type parameter, XPath Expression. The general syntax of using this strategy is as given below:

WebElement elem = driver.findElement(By.xpath(“ElementXPathExpression”));

Using XPath, we can locate a single element in various ways. It provides many different and easy ways to locate elements.

As an example let us take the following element in the page DemoQAAutomationPracticeForm :

find an element in Selenium by XPath

The XPath for the above button element is [@id="submit"]. Please refer How To Inspect Elements using Web Inspector for more information. So we use it in the findElement() command as below:

WebElement buttonLogin = driver.findElement(By.xpath("//button[@id = 'submit']"));

A program to find elements using By.XPath is as follows:

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

public class FindElementByXpath {
      public static void main(String[] args) {
	   System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		
           WebDriver driver = new Chrome
Driver();
   	   driver.get("https://demoqa.com/automation-practice-form");
	   WebElement buttonSubmit = driver.findElement( By.xpath("//button[@id = 'submit']"));
	   if(buttonSubmit != null) {
		System.out.println("Element found by xpath");
	   }
	}
}

This program displays the following output.

Program Output By XPath

Here we have provided the XPath of the "submit" button as an argument to the By.xpath locator. The program returns the element that matches the specified XPath.

How to use findElement() with Link Text/Partial Link Text in Selenium?

This strategy helps find links within the webpage. This means we can use this strategy to find elements of "a" (link) tags that have matching link names or partial link names.

The strategy accepts the value of the LINKTEXT attribute as a String type parameter.

The syntax of findElement() using this strategy is as seen below.

WebElement elem = driver.findElement(By.linkText(“Element LinkText”));

The above syntax is for using the findElement method using full link text. This is used when we know the link text that is used within the anchor (a) tag.

We can also use the partial link and find elements. The following is the syntax for the same:

WebElement elem = driver.findElement(By.partialLinkText(“ElementLinkText”));

Here we can provide partial link names.

As an example, we can take the following element (DemoQAHomeLink). We have highlighted the element as shown below:

find an element in Selenium by linkText partialLinkText

We can use a link strategy if the targeted text is link text. So for the above link element, the findElement() command for the link and partial link strategy is as follows:

WebElement element = driver.findElement(By.linkText("Home"));

//Or can be identified as 
WebElement element = driver.findElement(By.partialLinkText("HomehY");

In the first example, we use the By.linkText strategy and provide the entire 'linkname'. This will look for a link with the "Home" word. In the second example, we use By.partialLinkText and only provide a part of 'linkname' ('HomehY'). Since this is a partial link, it will look for links starting with 'HomehY'. As shown above, there is a link 'HomehYtil' on the page. So By.partialLinkText will find this link.

Let's implement code to use findElement with By.linkText/By.partialLinkText.

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

public class FindElementByLinkTextAndPartialLinkText {
	public static void main(String[] args) {
		System.setProperty("webdriver.chrome.driver", "C:/testSelenium/chromedriver.exe");		
		WebDriver driver = new ChromeDriver();
		driver.get("https://demoqa.com/links");
		WebElement element = driver.findElement (By.linkText("Home"));
		
		if(element != null) {
			System.out.println("Element found by LinkText");
		}
		
		element= driver.findElement (By.partialLinkText("HomehY");
		
		if(element!= null) {
			System.out.println("Element found by PartialLinkText");
		}
	}
}

Output:

Program Output By linkTextpartialLinkText

This program finds an element using By.linkText and By.partialLinkText locators. When By.linkText is specified, the 'findElement' matches the entire linkText specified. It matches the partial text when By.partialLinkText is specified.

Difference between findElement and findElements in Selenium

Let us discuss some differences between findElement() and findElements() methods provided by Selenium WebDriver.

FindElement() FindElements()
Returns the first web element out of all the elements found by the same locator. Finds and returns a list of web elements.
If no element matches the locator, an exception “NoSuchElementException” is thrown. No exception is thrown if no matching elements are found. Simply returns an empty list.
No indexing required since only one element is returned. Each web element is indexed starting from 0.
Best for finding a unique element on the web page. Best for performing actions on multiple elements at once.
Much faster than findElements because of it's core behavior Slower as it has to deal with finding multiple elements.
Indexing is not applicable here. Tester can access individual elements by index, e.g. elements.get(0)
Syntax: WebElement element = driver.findElement(By.locator("value")); List<WebElement> elements = driver.findElements(By.locator("value"));

Frequently Asked Questions (FAQs)

What is By class in Selenium?

The 'By' class in Selenium is an in-built class that helps locate elements on a web page using various locating strategies.

What are the 8 locators in Selenium?

The 8 locators in Selenium WebDriver used most commonly are ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath.

Selenium WebElement Commands
Selenium WebElement Commands
Previous Article
Handle CheckBox in Selenium WebDriver
Handle CheckBox in Selenium WebDriver
Next Article
Harish Rajora
I am a computer science engineer. I love to keep growing as the technological world grows. I feel there is no powerful tool than a computer to change the world in any way. Apart from my field of study, I like reading books a lot and developing new stuff.

Similar Articles

Feedback