ID Locator in Selenium
The ID Locator is one of the most commonly used and generally one of the simplest locator strategies in Selenium WebDriver. It is used to identify a web element through the value of its HTML id attribute.
When a web page contains an element with a unique id, Selenium can locate that element directly using By.id(). For example, if an input field contains id="username", Selenium can locate it using driver.findElement(By.id("username")).
ID locators are especially useful for automating login forms, registration forms, search boxes, buttons, checkboxes, radio buttons, and other interactive elements. Selenium training commonly covers locators such as ID, XPath, and CSS selectors as part of WebDriver element automation. :contentReference[oaicite:0]{index=0}
Learn more through the JustAcademy's Selenium Training Course and explore the available Selenium Course Demo Registration.
1. What is a Locator in Selenium?
A locator is a mechanism used by Selenium WebDriver to identify a particular element on a web page. Before Selenium can perform an action such as clicking, typing, selecting, or reading text, it must first locate the required WebElement.
Common Selenium locator strategies include:
- ID
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- CSS Selector
- XPath
The ID locator identifies an element using its HTML id attribute.
2. What is an ID Locator?
An ID Locator is a Selenium locator strategy that identifies an HTML element using its id attribute.
The basic Selenium syntax is:
driver.findElement(By.id("elementId"));
For example, consider the following HTML:
<input type="text" id="username" name="user" placeholder="Enter username">
The element can be located using:
driver.findElement(By.id("username"));
Here, username is the value of the HTML id attribute.
3. Basic Syntax of ID Locator
The Java Selenium syntax for an ID locator is:
By.id("idValue")
It is normally passed to the findElement() method:
WebElement element = driver.findElement(By.id("idValue"));
For example:
WebElement username = driver.findElement(By.id("username"));
4. Understanding the HTML id Attribute
The id attribute uniquely identifies an element within an HTML document. A typical HTML element may look like this:
<input id="email" type="email">
In this example:
input is the HTML tag.
id is the attribute.
email is the attribute value.
Selenium uses the value email to locate the element.
5. Simple ID Locator Example
Suppose a login page contains:
<input type="text" id="username">
<input type="password" id="password">
<button id="loginButton">Login</button>
Selenium code:
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("loginButton")).click();
This example demonstrates three different ID locators.
6. Why Use ID Locator?
ID is often a convenient locator because it directly targets the element's id attribute.
Important advantages include:
- Simple syntax.
- Easy to understand.
- Easy to maintain when IDs are stable.
- Usually requires less locator logic than complex XPath expressions.
- Useful for frequently accessed elements.
- Works naturally with Selenium's
By.id() strategy.
7. ID Locator with sendKeys()
The sendKeys() method is used to enter text into an input field.
driver.findElement(By.id("username")).sendKeys("John");
Example HTML:
<input type="text" id="username">
The Selenium script locates the element using its ID and enters the specified text.
8. ID Locator with click()
The click() method can be used after locating a button, checkbox, link, radio button, or another clickable element.
driver.findElement(By.id("loginButton")).click();
HTML:
<button id="loginButton">Login</button>
9. ID Locator with clear()
The clear() method removes existing text from an input field.
driver.findElement(By.id("username")).clear();
It is useful when an input field already contains a value and the automation script needs to replace it.
10. ID Locator with getText()
The getText() method retrieves visible text from an element.
String message = driver.findElement(By.id("successMessage")).getText();
System.out.println(message);
HTML:
<div id="successMessage">Login successful</div>
11. ID Locator with getAttribute()
The getAttribute() method can retrieve an attribute value from an element.
String value = driver.findElement(By.id("username")).getAttribute("value");
System.out.println(value);
This is useful when the value entered into an input field needs to be validated.
12. Locating a Text Field Using ID
<input type="text" id="firstName">
Selenium:
driver.findElement(By.id("firstName")).sendKeys("Rahul");
13. Locating a Password Field Using ID
<input type="password" id="password">
Selenium:
driver.findElement(By.id("password")).sendKeys("Pass@123");
14. Locating a Button Using ID
<button id="submitButton">Submit</button>
Selenium:
driver.findElement(By.id("submitButton")).click();
15. Locating a Checkbox Using ID
<input type="checkbox" id="terms">
Selenium:
WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}
16. Locating a Radio Button Using ID
<input type="radio" id="male" name="gender" value="male">
Selenium:
driver.findElement(By.id("male")).click();
17. Locating a Search Box Using ID
<input type="search" id="searchBox">
Selenium:
driver.findElement(By.id("searchBox")).sendKeys("Selenium WebDriver");
18. Locating a Link Using ID
<a id="homeLink" href="/home">Home</a>
Selenium:
driver.findElement(By.id("homeLink")).click();
19. Locating a Div Using ID
<div id="profile">
User Profile
</div>
Selenium:
String text = driver.findElement(By.id("profile")).getText();
System.out.println(text);
20. Locating an Element and Storing it in WebElement
Instead of directly performing an action, an element can be stored in a WebElement variable.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("admin");
This approach is useful when the same element needs to be used multiple times.
21. Import Statements for ID Locator
For a Java Selenium program, commonly required imports include:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
22. Complete Basic ID Locator Program
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class IdLocatorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("loginButton")).click();
driver.quit();
}
}
23. ID Locator in a Login Form
Consider the following login form:
<form>
<input type="text" id="username">
<input type="password" id="password">
<button id="login">Login</button>
</form>
Automation code:
driver.findElement(By.id("username")).sendKeys("john");
driver.findElement(By.id("password")).sendKeys("john123");
driver.findElement(By.id("login")).click();
24. ID Locator in a Registration Form
<input type="text" id="firstName">
<input type="text" id="lastName">
<input type="email" id="email">
<input type="password" id="password">
<button id="register">Register</button>
Selenium:
driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Smith");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Pass@123");
driver.findElement(By.id("register")).click();
25. ID Locator in a Search Form
<input id="search" type="text">
<button id="searchButton">Search</button>
driver.findElement(By.id("search")).sendKeys("Laptop");
driver.findElement(By.id("searchButton")).click();
26. ID Locator for a Checkbox
A checkbox can be selected conditionally to avoid clicking it when it is already selected.
WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
27. ID Locator for a Radio Button
WebElement maleRadio = driver.findElement(By.id("male"));
if (!maleRadio.isSelected()) {
maleRadio.click();
}
28. ID Locator for Multiple Elements
When multiple elements need to be handled, findElements() can be used.
List<WebElement> elements = driver.findElements(By.id("product"));
However, an ID is normally expected to identify one unique element. If the same ID appears on multiple elements, the HTML is not following the normal uniqueness expectation for IDs, and automation can become ambiguous.
29. ID Should Normally Be Unique
Consider:
<input id="username">
<input id="password">
Each element has a different ID. This makes the elements easy to distinguish.
Using the same ID repeatedly is poor HTML practice:
<input id="username">
<input id="username">
Automation scripts should avoid depending on duplicated IDs.
30. ID Locator vs Name Locator
| Feature | ID Locator | Name Locator |
| Syntax | By.id("username") | By.name("username") |
| Attribute | id | name |
| Common Use | Unique elements | Form fields |
| Example | id="username" | name="username" |
31. ID Locator vs Class Name
| Feature | ID | Class Name |
| HTML Attribute | id | class |
| Java Syntax | By.id() | By.className() |
| Typical Purpose | Unique identification | Grouping/styling |
| Example | id="login" | class="btn" |
32. ID Locator vs XPath
| Feature | ID | XPath |
| Syntax | By.id() | By.xpath() |
| Complexity | Simple | Can be simple or complex |
| Attribute Support | ID attribute | Many attributes and relationships |
| Text Matching | No direct text matching | Yes |
| Axes | No | Yes |
| Typical Use | Stable unique ID | Complex or dynamic elements |
33. ID Locator vs CSS Selector
An ID can also be represented in CSS selector syntax using #.
#username
Selenium CSS example:
driver.findElement(By.cssSelector("#username"));
For a direct ID locator, Selenium provides:
driver.findElement(By.id("username"));
34. When Should You Prefer an ID Locator?
An ID locator is particularly suitable when the application's ID is:
- Unique.
- Stable across test runs.
- Meaningful and predictable.
- Not generated randomly on every page load.
- Not frequently changed by developers.
35. Stable ID Example
<input id="emailAddress" type="email">
This is a clear and readable ID.
driver.findElement(By.id("emailAddress")).sendKeys("[email protected]");
36. Dynamic ID Example
Some applications generate IDs dynamically.
<input id="input_12345" type="text">
On another execution, the ID might become:
<input id="input_98765" type="text">
In this situation, directly using By.id() with the changing value may make the automation script unstable.
37. Why Dynamic IDs Can Be a Problem
If the ID changes every time the application loads, the locator written in the automation script may no longer match the element.
For example:
driver.findElement(By.id("input_12345"));
If the application generates input_67890 during the next execution, Selenium may throw NoSuchElementException.
38. Handling Dynamic IDs
When an ID is dynamic, inspect the HTML and identify another stable attribute or relationship.
For example:
<input id="user_12345" name="username" type="text">
If the name attribute is stable, it may be used instead:
driver.findElement(By.name("username"));
Alternatively, a CSS selector or XPath can be used when appropriate.
39. ID Locator with Explicit Wait
Sometimes an element has a valid ID but is not immediately available for interaction. An explicit wait can be used.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("username"))
);
username.sendKeys("admin");
40. ID Locator with ElementToBeClickable
For buttons and other interactive elements, waiting until the element is clickable can be useful.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement login = wait.until(
ExpectedConditions.elementToBeClickable(By.id("loginButton"))
);
login.click();
41. Required Imports for Explicit Wait
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
42. ID Locator with Page Object Model
In the Page Object Model, locators can be stored as class fields so that page interaction logic remains organized.
public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
private By password = By.id("password");
private By loginButton = By.id("loginButton");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginButton).click();
}
}
43. Benefits of ID Locators in POM
- Locators remain centralized.
- Page classes are easier to maintain.
- Changes can be made in one place.
- Test classes become cleaner.
- Reusable page actions can be created.
44. ID Locator with TestNG
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void loginTest() {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("loginButton")).click();
driver.quit();
}
}
45. Verifying an Element Located by ID
The isDisplayed() method can be used to check whether the located element is visible.
WebElement message = driver.findElement(By.id("successMessage"));
if (message.isDisplayed()) {
System.out.println("Success message is displayed.");
}
46. Checking Whether an ID Element Is Enabled
WebElement button = driver.findElement(By.id("submit"));
if (button.isEnabled()) {
System.out.println("Button is enabled.");
}
47. Checking Whether an ID Element Is Selected
This is useful for checkboxes and radio buttons.
WebElement checkbox = driver.findElement(By.id("terms"));
if (checkbox.isSelected()) {
System.out.println("Checkbox is selected.");
}
48. Checking Element Attributes
WebElement email = driver.findElement(By.id("email"));
System.out.println(email.getAttribute("type"));
System.out.println(email.getAttribute("placeholder"));
System.out.println(email.getAttribute("value"));
49. Common ID Locator Errors
Several Selenium exceptions can occur when working with ID locators.
| Exception | Possible Cause |
| NoSuchElementException | ID does not exist or element is not available |
| StaleElementReferenceException | DOM changed after the element was located |
| ElementNotInteractableException | Element exists but cannot currently be interacted with |
| ElementClickInterceptedException | Another element is blocking the click |
| TimeoutException | Explicit wait condition was not satisfied |
50. NoSuchElementException with ID
Example:
driver.findElement(By.id("wrongId")).click();
If wrongId does not exist on the current page, Selenium may throw NoSuchElementException.
Check the following:
- Is the ID correct?
- Is the correct page open?
- Is the element inside an iframe?
- Does the element appear dynamically?
- Has the DOM changed?
51. ID Locator and Iframes
If the element is inside an iframe, Selenium must switch to that iframe before locating the inner element.
WebElement frame = driver.findElement(By.id("paymentFrame"));
driver.switchTo().frame(frame);
driver.findElement(By.id("cardNumber")).sendKeys("4111111111111111");
driver.switchTo().defaultContent();
52. ID Locator and Multiple Windows
An ID locator works within the currently active browsing context. If a new window or tab opens, Selenium must switch to the correct window before locating the element.
String originalWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(originalWindow)) {
driver.switchTo().window(window);
break;
}
}
driver.findElement(By.id("newWindowElement")).click();
53. ID Locator and Shadow DOM
Elements inside a Shadow DOM may require Shadow Root handling rather than ordinary document-level locating.
An ID visible inside a shadow tree cannot always be located simply with:
driver.findElement(By.id("shadowElement"));
The correct approach depends on how the application implements the Shadow DOM and the Selenium/WebDriver APIs being used.
54. ID Locator for Dynamic Web Applications
Modern applications frequently update the DOM using JavaScript, AJAX, React, Angular, Vue, or other frameworks. In such cases, an ID may exist only after a particular action or API response.
A wait can help synchronize the automation script with the application.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.presenceOfElementLocated(By.id("dynamicElement"))
);
55. Presence vs Visibility
| Condition | Purpose |
| presenceOfElementLocated | Checks that the element exists in the DOM |
| visibilityOfElementLocated | Checks that the element exists and is visible |
| elementToBeClickable | Checks that the element can be interacted with for clicking |
56. ID Locator with CSS Selector
An element with ID username can also be located using CSS:
driver.findElement(By.cssSelector("#username"));
The # symbol represents an ID selector in CSS.
57. ID Locator with XPath
The same element can be located using XPath:
driver.findElement(By.xpath("//*[@id='username']"));
However, if a stable unique ID is directly available, By.id("username") is usually simpler.
58. ID Locator for a Product Search Page
<input id="productSearch" type="text">
<button id="searchProduct">Search</button>
driver.findElement(By.id("productSearch")).sendKeys("Laptop");
driver.findElement(By.id("searchProduct")).click();
59. ID Locator for E-Commerce Cart
<button id="addToCart">Add to Cart</button>
<button id="checkout">Checkout</button>
driver.findElement(By.id("addToCart")).click();
driver.findElement(By.id("checkout")).click();
60. ID Locator for a Navigation Menu
<a id="home" href="/home">Home</a>
<a id="products" href="/products">Products</a>
<a id="contact" href="/contact">Contact</a>
driver.findElement(By.id("products")).click();
61. ID Locator for a Form Submit
<button type="submit" id="submitForm">Submit Form</button>
driver.findElement(By.id("submitForm")).click();
62. ID Locator for Error Messages
<span id="emailError">Invalid email address</span>
String error = driver.findElement(By.id("emailError")).getText();
if (error.equals("Invalid email address")) {
System.out.println("Validation message verified.");
}
63. ID Locator for Success Messages
<div id="successMessage">Registration successful</div>
String message = driver.findElement(By.id("successMessage")).getText();
System.out.println(message);
64. ID Locator for Hidden Elements
An element may exist in the DOM but not be visible.
<div id="hiddenMessage" style="display:none">Hidden Message</div>
Selenium may locate the element:
WebElement message = driver.findElement(By.id("hiddenMessage"));
But attempting an interaction such as clicking or typing may fail because the element is not visible or interactable.
65. ID Locator for Disabled Elements
<button id="submitButton" disabled>Submit</button>
Selenium can locate the element, but the element may not be interactable while disabled.
WebElement submit = driver.findElement(By.id("submitButton"));
System.out.println(submit.isEnabled());
66. ID Locator Best Practices
- Prefer stable IDs when they are available.
- Verify that the ID is unique.
- Avoid dynamically generated IDs when a stable alternative exists.
- Do not hard-code IDs that frequently change.
- Use meaningful page object variables.
- Use explicit waits for dynamically loaded elements.
- Keep locators centralized in Page Object classes.
- Inspect the DOM before creating a locator.
- Do not use unnecessary complex XPath when a stable ID is available.
- Keep automation locators readable.
67. Common Mistakes with ID Locator
Mistake 1: Typing the Wrong ID
driver.findElement(By.id("userName"));
If the actual ID is username, the locator will not match.
Mistake 2: Ignoring Case
HTML attribute values are generally case-sensitive for locator matching. These are different values:
id="username"
id="UserName"
Mistake 3: Using a Changing ID
Generated IDs can change between executions and make tests unstable.
Mistake 4: Not Checking the Current Page
A valid ID on another page will not locate an element if the browser is currently on a different page.
Mistake 5: Ignoring Frames
An element inside an iframe requires switching into the correct frame first.
68. ID Locator Naming in Page Objects
Meaningful variable names improve readability.
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By loginButton = By.id("loginButton");
This is easier to understand than:
private By element1 = By.id("username");
private By element2 = By.id("password");
private By element3 = By.id("loginButton");
69. Reusable ID Locator Utility
public void enterText(By locator, String text) {
driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(text);
}
Usage:
enterText(By.id("username"), "admin");
enterText(By.id("email"), "[email protected]");
70. Reusable Click Utility
public void click(By locator) {
driver.findElement(locator).click();
}
Usage:
click(By.id("loginButton"));
click(By.id("submitButton"));
71. ID Locator with Explicit Wait Utility
public WebElement waitForElement(By locator) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
Usage:
WebElement username = waitForElement(By.id("username"));
username.sendKeys("admin");
72. Real-World Login Automation Example
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
WebElement login = driver.findElement(By.id("loginButton"));
username.sendKeys("admin");
password.sendKeys("admin123");
login.click();
driver.quit();
73. Real-World Registration Automation Example
driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Smith");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Pass@123");
driver.findElement(By.id("confirmPassword")).sendKeys("Pass@123");
driver.findElement(By.id("registerButton")).click();
74. Real-World Search Automation Example
WebElement search = driver.findElement(By.id("searchBox"));
search.sendKeys("Selenium WebDriver");
driver.findElement(By.id("searchButton")).click();
75. Real-World Checkout Example
driver.findElement(By.id("addToCart")).click();
driver.findElement(By.id("cart")).click();
driver.findElement(By.id("checkout")).click();
76. ID Locator Validation Checklist
- Inspect the HTML element.
- Find the
id attribute.
- Confirm the ID value.
- Check whether the ID is stable.
- Check whether the ID is unique.
- Write the
By.id() locator.
- Test the locator in Selenium.
- Add an appropriate wait if required.
- Validate the resulting WebElement.
- Move the locator into the Page Object if building a framework.
77. ID Locator Decision Flow
Start
|
v
Inspect Web Element
|
v
Does it have an ID?
|
+---- No ----> Consider Name / Class / CSS / XPath
|
Yes
|
v
Is the ID unique?
|
+---- No ----> Find a more reliable locator
|
Yes
|
v
Is the ID stable?
|
+---- No ----> Find a stable attribute or relationship
|
Yes
|
v
Use By.id("value")
|
v
Add appropriate wait if required
|
v
Perform WebElement action
78. ID Locator Example with Assertions
WebElement message = driver.findElement(By.id("successMessage"));
String actualMessage = message.getText();
Assert.assertEquals(actualMessage, "Registration successful");
79. ID Locator with TestNG Assertion
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyMessage() {
WebElement message = driver.findElement(By.id("successMessage"));
Assert.assertTrue(message.isDisplayed());
}
80. ID Locator in Data-Driven Testing
The locator can remain constant while the test data changes.
String username = "admin";
String password = "admin123";
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("loginButton")).click();
81. ID Locator in Automation Frameworks
ID locators are frequently stored inside Page Object classes, utility classes, or locator repositories. This allows the test framework to separate element identification from test execution logic.
A typical structure can be:
src
├── pages
│ └── LoginPage.java
├── tests
│ └── LoginTest.java
├── utilities
│ └── WebDriverUtility.java
└── testdata
└── loginData.xlsx
82. Advantages of ID Locator
- Simple syntax.
- Easy to read.
- Easy for beginners to understand.
- Useful for unique elements.
- Can make Page Objects readable.
- Reduces unnecessary locator complexity.
- Works well for stable application IDs.
83. Limitations of ID Locator
- Not every element has an ID.
- Some applications generate dynamic IDs.
- Duplicated IDs can create ambiguity.
- Changing IDs can break automation.
- ID alone cannot express complex DOM relationships.
- Elements inside special contexts such as iframes or Shadow DOM may require additional handling.
84. ID Locator and Maintainability
A locator is maintainable when it continues to identify the intended element despite normal UI changes.
For example, this is generally more readable:
By.id("loginButton")
than a long XPath when the element already has a stable ID.
85. ID Locator and Readability
Readable locators help automation engineers quickly understand what element a test is interacting with.
driver.findElement(By.id("email")).sendKeys("[email protected]");
The purpose of the statement is immediately clear.
86. ID Locator and Test Stability
A stable ID can contribute to stable automation because the locator directly targets the intended element rather than relying on a long DOM hierarchy.
However, locator stability ultimately depends on the application's HTML implementation and whether the ID remains unchanged.
87. ID Locator Interview Question: What is an ID Locator?
Answer: An ID Locator is a Selenium WebDriver locator strategy used to identify a web element using the value of its HTML id attribute. In Java Selenium, it is commonly written as driver.findElement(By.id("value")).
88. Interview Question: How Do You Use ID Locator?
Answer:
driver.findElement(By.id("username"));
For entering text:
driver.findElement(By.id("username")).sendKeys("admin");
89. Interview Question: Why Is ID Commonly Used?
Answer: ID is convenient because it directly identifies an element through the HTML id attribute. When the ID is unique and stable, the locator is simple and readable.
90. Interview Question: What If the ID Is Dynamic?
Answer: If the ID changes dynamically, directly using the changing value may make the locator unreliable. The tester should inspect the element for another stable attribute or use an appropriate CSS selector or XPath strategy.
91. Interview Question: Can Two Elements Have the Same ID?
Answer: An ID is intended to identify an element uniquely within a document. If multiple elements use the same ID, the HTML structure does not provide the expected uniqueness, and automation based on that ID can become ambiguous.
92. Interview Question: Can ID Be Used with findElements()?
Answer: Yes, Selenium allows findElements(By.id("value")), but an ID is normally intended to identify one unique element. If multiple matching elements are returned because of duplicate IDs, the HTML should be inspected.
93. Interview Question: ID vs XPath?
Answer: ID is direct and simple when a stable ID is available. XPath supports more complex matching, text conditions, DOM relationships, and axes. The locator should be selected according to the structure and stability of the application.
94. Interview Question: ID vs CSS Selector?
Answer: An ID can be directly located using By.id(), while CSS can use an ID selector such as #username. CSS selectors also support many additional attribute and relationship patterns.
95. Interview Question: Can ID Locator Handle Dynamic Web Elements?
Answer: Yes, if the element has a stable ID at the time it is located. If the element appears dynamically, an appropriate wait may be required. If the ID itself changes, another stable locator strategy may be necessary.
96. Interview Question: What Exception Occurs When an ID Is Incorrect?
Answer: Selenium commonly throws NoSuchElementException when it cannot find the element matching the supplied locator in the current browsing context.
97. Interview Question: Can ID Locator Be Used Inside an iframe?
Answer: Yes, but Selenium must first switch to the iframe containing the element. After switching to the correct frame, the ID locator can be used normally.
98. Interview Question: Can ID Locator Be Used for Buttons?
Answer: Yes. For example:
driver.findElement(By.id("submitButton")).click();
99. Interview Question: Can ID Locator Be Used for Checkboxes?
Answer: Yes. For example:
WebElement checkbox = driver.findElement(By.id("terms"));
if (!checkbox.isSelected()) {
checkbox.click();
}
100. Interview Question: Can ID Locator Be Used for Radio Buttons?
Answer: Yes. A radio button can be located by its ID and clicked if it is not already selected.
WebElement radio = driver.findElement(By.id("male"));
if (!radio.isSelected()) {
radio.click();
}
101. Practical Project: Login Page Using ID Locators
Build an automation script for a login page using ID locators for the username field, password field, login button, and success message.
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("admin123");
driver.findElement(By.id("loginButton")).click();
WebElement message = driver.findElement(By.id("successMessage"));
System.out.println(message.getText());
102. Practical Project: Registration Form
Create an automation script that fills a registration form using ID locators.
driver.findElement(By.id("firstName")).sendKeys("John");
driver.findElement(By.id("lastName")).sendKeys("Smith");
driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("Pass@123");
driver.findElement(By.id("confirmPassword")).sendKeys("Pass@123");
WebElement terms = driver.findElement(By.id("terms"));
if (!terms.isSelected()) {
terms.click();
}
driver.findElement(By.id("registerButton")).click();
103. Practical Project: E-Commerce Search
driver.get("https://example.com/products");
driver.findElement(By.id("searchBox")).sendKeys("Laptop");
driver.findElement(By.id("searchButton")).click();
driver.findElement(By.id("addToCart")).click();
driver.findElement(By.id("cartButton")).click();
driver.findElement(By.id("checkoutButton")).click();
104. Practical Project: Form Validation
driver.findElement(By.id("email")).sendKeys("invalid-email");
driver.findElement(By.id("submitButton")).click();
WebElement error = driver.findElement(By.id("emailError"));
System.out.println(error.getText());
105. ID Locator Workflow
Open Web Page
|
v
Inspect HTML
|
v
Find id Attribute
|
v
Check ID Stability
|
v
Create By.id()
|
v
Locate WebElement
|
v
Apply Action
|
v
Validate Result
106. ID Locator Quick Reference
| Action | Example |
| Locate | driver.findElement(By.id("username")) |
| Type | driver.findElement(By.id("username")).sendKeys("admin") |
| Clear | driver.findElement(By.id("username")).clear() |
| Click | driver.findElement(By.id("login")).click() |
| Get Text | driver.findElement(By.id("message")).getText() |
| Get Attribute | driver.findElement(By.id("email")).getAttribute("value") |
| Displayed | driver.findElement(By.id("message")).isDisplayed() |
| Enabled | driver.findElement(By.id("submit")).isEnabled() |
| Selected | driver.findElement(By.id("terms")).isSelected() |
107. ID Locator Best-Practice Summary
| Practice | Recommendation |
| Unique ID | Prefer IDs that uniquely identify one element. |
| Stable ID | Prefer IDs that do not change between executions. |
| Readable ID | Use meaningful IDs when the application provides them. |
| Dynamic ID | Look for stable alternatives when IDs are generated dynamically. |
| Waits | Use synchronization when elements appear asynchronously. |
| POM | Store locators in Page Object classes for maintainability. |
| Validation | Verify the resulting page state after interactions. |
108. Complete ID Locator Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CompleteIdLocatorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com/login");
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
WebElement password = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
username.sendKeys("admin");
password.sendKeys("admin123");
loginButton.click();
WebElement successMessage = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("successMessage")
)
);
System.out.println(successMessage.getText());
} finally {
driver.quit();
}
}
}
109. ID Locator Checklist for Automation Testers
- Understand the HTML structure.
- Locate the element's ID.
- Verify the ID value carefully.
- Check whether the ID is unique.
- Check whether the ID remains stable.
- Use
By.id() for a stable ID.
- Use
findElement() for a single target element.
- Use
findElements() when multiple matches are intentionally required.
- Use waits for dynamic content.
- Switch to the correct iframe when required.
- Use Page Object Model in larger frameworks.
- Validate the expected result after performing the action.
110. Conclusion
The ID Locator is an important Selenium WebDriver locator strategy used to identify elements through their HTML id attribute. Its syntax is simple: By.id("idValue").
When an element has a unique and stable ID, using an ID locator can make Selenium automation code simple, readable, and maintainable. ID locators can be used with text fields, passwords, buttons, links, checkboxes, radio buttons, messages, search fields, and many other WebElements.
For dynamic applications, testers should verify whether the ID remains stable and use appropriate waits or alternative locator strategies when necessary. Understanding ID locators provides a strong foundation for learning other Selenium locator strategies such as Name, Class Name, CSS Selector, and XPath.
For structured Selenium automation learning, explore the JustAcademy's Selenium Training Course.
To explore the course and request a demo, visit Register for Course Demo.