Overview
The ByIdOrName class is a composite element locator that first attempts to find elements by their id attribute and falls back to searching by name attribute.
Description
ByIdOrName extends the Selenium By class and implements Serializable. It provides a dual-strategy element location mechanism: when finding a single element, it first tries to locate by id and, if a NoSuchElementException is thrown, falls back to locating by name. When finding multiple elements, it aggregates results from both id and name searches. This class is used internally by the How.ID_OR_NAME enum constant in the Page Factory pattern.
Usage
Use ByIdOrName when you have an identifier string that could match either an element's id or name attribute and you want a single locator to handle both cases. This is commonly used with the @FindBy(how = How.ID_OR_NAME) annotation in the Page Object pattern.
Code Reference
Source Location
Signature
public class ByIdOrName extends By implements Serializable {
public ByIdOrName(String idOrName);
public WebElement findElement(SearchContext context);
public List<WebElement> findElements(SearchContext context);
public String toString();
}
Import
import org.openqa.selenium.support.ByIdOrName;
I/O Contract
Constructor
| Parameter |
Type |
Description
|
idOrName |
String |
The value to search for as both an element id and name attribute
|
Methods
| Method |
Parameters |
Returns |
Description
|
findElement |
SearchContext context |
WebElement |
Finds a single element: tries By.id() first, falls back to By.name() if NoSuchElementException is thrown
|
findElements |
SearchContext context |
List<WebElement> |
Finds all matching elements: aggregates results from both By.id() and By.name()
|
toString() |
none |
String |
Returns by id or name "value"
|
Search Strategy
| Operation |
Step 1 |
Step 2 |
Behavior
|
findElement |
Try By.id(idOrName) |
On NoSuchElementException, try By.name(idOrName) |
Returns first match; throws if neither finds a result
|
findElements |
Collect all from By.id(idOrName) |
Append all from By.name(idOrName) |
Returns combined list; may contain duplicates if an element has matching id and name
|
Usage Examples
// Direct usage
WebElement element = driver.findElement(new ByIdOrName("username"));
// Find all elements matching by id or name
List<WebElement> elements = driver.findElements(new ByIdOrName("email"));
// Used with Page Factory annotation
public class LoginPage {
@FindBy(how = How.ID_OR_NAME, using = "username")
private WebElement usernameField;
@FindBy(how = How.ID_OR_NAME, using = "password")
private WebElement passwordField;
}
Related Pages
Page Connections
Double-click a node to navigate. Hold to expand connections.