📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

Beginner’s Guide to findElement in Selenium Testing

Rohit Rajpal
Learn how to use findElement and findElements in Selenium with syntax, locator strategies, real-world examples, and best practices.
Beginners Guide to findElement in Selenium Testing

In Selenium, every automated action starts with locating elements on a web page. If the element cannot be found, the test cannot proceed. This makes element identification one of the most critical parts of building reliable automation.

Selenium gives two commands for this task: findElement and findElements. findElement is used when you want a single element and it stops the execution with a NoSuchElementException if nothing is found. findElements is used when multiple elements may exist and it returns a list, even if that list is empty.

This guide goes into the exact behavior of both commands, their syntax, and real examples across different locator strategies.

Overview of findElement in Selenium

The findElement command is used to locate a single web element on a page. Once the element is found, you can perform actions on it such as click, type text, or read its value.

The key point about findElement is that it always returns the first matching element based on the locator strategy you provide. If there are multiple matches, only the first one in the DOM order is returned.

If no element is found, Selenium throws a NoSuchElementException. This is why findElement is often paired with waits. Without proper waits, the test may fail because the element was not loaded when Selenium tried to access it.

Testers typically use findElement when they know only one element should match the locator, such as a login button, a search box, or a page title. In these cases, expecting multiple matches would indicate either a bad locator or an issue in the application.

How findElement and findElements Work Differently

Even though findElement and findElements rely on the same locator strategies, the way they behave once executed is different. These differences influence how you design your locators, how you handle errors, and how you control the flow of your test cases. Below are the main distinctions, explained in detail.

1. Return type

The first difference lies in what each method gives back to your script. The type of object you receive decides whether you interact with a single element or a group of elements.

  • findElement returns a single WebElement. This makes it suitable for direct actions like .click(), .sendKeys(), or .getText().
  • findElements returns a List<WebElement>. You cannot perform actions on the list directly. Instead, you loop through it or use conditions like list.size() to work with the elements.

2. Handling multiple matches

When the locator you provide matches more than one element in the DOM, Selenium applies different rules depending on which method you use.

  • findElement selects only the first element that appears in the DOM order, ignoring the rest. This means if you are not precise with your locator, you may end up interacting with the wrong element.
  • findElements collects every element that matches. This is helpful when you need to validate multiple items on a page, such as verifying all links in a navigation bar or checking the values in a table column.

3. When no match is found

The way each method behaves when no element exists for the locator can change how stable your tests are.

  • findElement throws a NoSuchElementException. Unless you use waits or try-catch blocks, the test will stop at that point. This strict behavior is useful when the presence of an element is mandatory.
  • findElements returns an empty list. Your test keeps running, and you can add logic to decide what should happen if the list is empty, such as skipping a step or logging the absence of elements.

4. Practical use cases

Deciding which method to use depends on the nature of the element and the intent of your test.

  • Use findElement when you are certain the element exists and is unique, such as a login button, a page title, or a search field.
  • Use findElements when multiple elements are expected or possible, such as product items, error messages, or menu options. This approach allows you to validate collections and handle variations in page design.

findElement Command Syntax

The findElement method is used to locate a single element on a page. It always requires two things: a WebDriver instance and a locator strategy. If the element exists, Selenium returns it as a WebElement. If the element does not exist, Selenium throws a NoSuchElementException.

The generic syntax is:

				
					WebElement element = driver.findElement(By.<locatorStrategy>("locatorValue"));
				
			

Each part of this syntax has a specific role:

  • WebElement element: a variable that stores the element returned by Selenium. You can then use it to perform actions like .click(), .sendKeys(), or .getText().
  • driver: the WebDriver instance that controls the browser session. All element searches begin with this object.
  • findElement: the Selenium method that retrieves the first element matching the given locator.
  • By.<locatorStrategy>: the class that defines how Selenium should search. Locator options include id, name, className, tagName, linkText, partialLinkText, cssSelector, and XPath.
  • “locatorValue”: the actual identifier for the element, such as the ID value, name, or XPath expression.

Example:

				
					WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
				
			

In this example, Selenium looks for the element with the name attribute q, assigns it to searchBox, and then types into it.

findElements Command Syntax

The findElements method is used when you need to locate multiple elements on a page. Instead of returning a single element, it gives you a list of all matching elements. If no element matches the locator, Selenium returns an empty list. This behavior allows your test to continue running without throwing an exception, giving you the flexibility to handle zero, one, or many results.

The generic syntax is:

				
					List<WebElement> elements = driver.findElements(By.<locatorStrategy>("locatorValue"));
				
			

Each part of this syntax has a specific role:

  • List<WebElement> elements: a collection that stores all the elements found by Selenium. You can loop through this list or check its size.
  • driver: the WebDriver instance that controls the browser session.
    findElements: the Selenium method that retrieves every element matching the provided locator.
  • By.<locatorStrategy>: the class that specifies how Selenium should search for elements. Supported strategies are the same as findElement, including id, name, className, tagName, linkText, partialLinkText, cssSelector, and XPath.
  • “locatorValue”: the actual identifier used to locate the elements.

Example:

				
					List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Number of links: " + links.size());
				
			

In this example, Selenium finds all the <a> elements on the page, stores them in a list, and prints the total count.

Using findElement in Real Test Cases

The power of findElement lies in its ability to work with different locator strategies. Each strategy has its own advantages and limitations, and choosing the right one can determine whether your test scripts are stable or fragile.

Below are the most common ways testers identify elements in real-world projects.

1. Identifying Elements with ID

Using the element’s ID is the most reliable and preferred method in Selenium because IDs are unique within a page. If an element has an ID attribute, it should be your first choice.

Key points to note:

  • Uniqueness: IDs are expected to be unique across the page, which reduces the chance of ambiguous matches.
  • Performance: Locating by ID is faster than other strategies.
  • Best practice: Always prefer IDs when available, but avoid hardcoding IDs if they are dynamically generated.

Example:

				
					WebElement loginButton = driver.findElement(By.id("loginBtn"));
loginButton.click();
				
			

2. Identifying Elements with Name

The name attribute is another common locator, especially for input fields in forms. It works well when IDs are missing.

Key points to note:

  • Suitability: Often used for text fields, radio buttons, and checkboxes.
  • Ambiguity risk: Multiple elements can share the same name, so ensure you are not unintentionally selecting the wrong one.
  • Fallback: Useful as a backup when IDs are not provided.

Example:

				
					WebElement usernameField = driver.findElement(By.name("username"));
usernameField.sendKeys("testuser");
				
			

3. Identifying Links by LinkText

For hyperlinks, Selenium allows identification using the visible text between the <a> tags.

Key points to note:

  • Readability: Locator is human-friendly since it uses visible text.
  • Exact match: The link text must match exactly, including spaces and case.
  • Use case: Works best when links have stable, unique text.

Example:

				
					WebElement aboutLink = driver.findElement(By.linkText("About Us"));
aboutLink.click();
				
			

4. Identifying with CSS Selector

CSS selectors are powerful and flexible. They allow you to pinpoint elements using IDs, classes, attributes, or hierarchical relationships.

Key points to note:

  • Flexibility: Can locate elements using combinations of attributes.
  • Performance: Typically faster than XPath.
  • Complexity: Can become hard to read if overused with deeply nested selectors.

Example:

				
					WebElement searchBox = driver.findElement(By.cssSelector("input[name='q']"));
searchBox.sendKeys("Selenium WebDriver");
				
			

5. Identifying with XPath

XPath is the most versatile locator strategy. It can find elements based on hierarchy, attributes, partial matches, or text content.

Key points to note:

  • Versatility: Supports both absolute and relative paths.
  • Usefulness: Can locate elements when no ID, name, or CSS class is available.
  • Performance impact: More resource-intensive than ID or CSS, especially with complex expressions.

Example:

				
					WebElement passwordField = driver.findElement(By.xpath("//input[@type='password']"));
passwordField.sendKeys("securePass");
				
			

Best Practices for Using findElement and findElements

Choosing the right locator and handling the results correctly can make the difference between a stable test suite and one that breaks frequently. Both findElement and findElements are powerful, but they need to be used with care. Below are best practices followed by experienced testers to avoid common issues.

  • Prefer unique locators: Always start with IDs when available, since they are unique and fast. Fall back to name, CSS, or XPath only if necessary.
  • Use relative XPath over absolute: Relative XPath (//input[@id=’username’]) is less fragile than absolute XPath (/html/body/div[2]/form/input[1]).
  • Handle missing elements properly: For findElement, use waits (WebDriverWait) to reduce NoSuchElementException. For findElements, check list.size() before performing actions.
  • Avoid brittle locators: Do not rely on auto-generated or dynamic attributes that change on page refresh. Instead, combine stable attributes or use CSS/XPath patterns.
  • Use explicit waits for dynamic content: Pages with JavaScript often load elements late. Explicit waits ensure the test does not fail because the element is not yet visible.
  • Limit overuse of findElements: Large collections can slow down tests. Retrieve only what you need, especially on pages with many elements.

Conclusion

Locating elements with findElement and findElements is central to Selenium automation. These methods define how tests interact with the application, whether it is clicking buttons, filling forms, or validating page content.

For reliable execution across browsers and devices, tests should run in environments that reflect real user conditions. BrowserStack provides access to 3,500+ real browsers and devices, allowing testers to validate their Selenium scripts beyond local setups. This ensures that element locators work consistently, even in varied operating systems and browser versions.

Frequently Asked Questions

1. Can findElement locate elements inside iframes?

Yes, but only after switching the driver’s context to the iframe. Selenium cannot access elements inside an iframe directly. Use driver.switchTo().frame() to move into the iframe first, then use findElement. After finishing, switch back to the default content using driver.switchTo().defaultContent().

2. What’s the difference between implicit wait and explicit wait when using findElement?

Implicit wait tells Selenium to keep polling the DOM for a set duration when trying to find an element. Explicit wait applies to a specific element and condition, such as waiting until it is visible or clickable. Explicit waits give finer control, especially for dynamic content.

3. Why does Selenium throw a NoSuchElementException?

This happens when findElement cannot locate an element using the provided locator. The common causes include incorrect locators, elements not yet loaded, or elements inside iframes without switching context. Adding waits or verifying locators in browser dev tools usually resolves the issue.

4. Can findElements be chained with other Selenium methods?

Yes. Since findElements returns a list of WebElement objects, you can chain actions on individual elements. For example, driver.findElements(By.tagName(“a”)).get(0).click() clicks the first link. You can also iterate over the list and perform actions on each element.

Written by
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.

Related posts