We use findElement by ID to quickly find a single web page element using its unique ID. This helps us interact with that element in tests.
findElement by ID in Selenium Java
WebElement element = driver.findElement(By.id("elementID"));The By.id locator finds the first element with the matching ID attribute.
ID values should be unique on the page for this to work reliably.
loginBtn to click or check.WebElement loginButton = driver.findElement(By.id("loginBtn"));username.WebElement usernameField = driver.findElement(By.id("username"));error-msg to verify its text.WebElement errorMessage = driver.findElement(By.id("error-msg"));This test opens a login page, enters username and password by locating inputs with their IDs, clicks the login button, then checks if the success message with a specific ID appears with expected text.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FindElementByIdExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/login"); // Find username input by ID and enter text WebElement username = driver.findElement(By.id("username")); username.sendKeys("testuser"); // Find password input by ID and enter text WebElement password = driver.findElement(By.id("password")); password.sendKeys("mypassword"); // Find login button by ID and click WebElement loginBtn = driver.findElement(By.id("loginBtn")); loginBtn.click(); // Verify login success message by ID WebElement successMsg = driver.findElement(By.id("successMsg")); String message = successMsg.getText(); if (message.equals("Login successful")) { System.out.println("Test Passed: Login success message found."); } else { System.out.println("Test Failed: Unexpected message: " + message); } } finally { driver.quit(); } } }
Always ensure the ID you use is unique on the page to avoid unexpected results.
If the element with the given ID is not found, Selenium throws a NoSuchElementException.
Use explicit waits if the element may take time to appear before interacting.
findElement by ID locates a single element using its unique ID attribute.
It is fast and reliable when IDs are unique and stable.
Use it to interact with buttons, inputs, or any element with a known ID.
Practice
findElement(By.id("submitBtn")) do?Solution
Step 1: Understand the method purpose
The methodfindElementlocates a single web element on the page.Step 2: Analyze the locator used
UsingBy.id("submitBtn")means it looks for an element with the exact ID "submitBtn".Final Answer:
Finds the first element on the page with the ID "submitBtn". -> Option BQuick Check:
findElement + By.id = single element by ID [OK]
- Confusing findElement with findElements (plural)
- Using class name or tag name instead of ID
- Assuming it returns multiple elements
Solution
Step 1: Recall correct method syntax
The methodBy.idis called with parentheses and a string argument, likeBy.id("username").Step 2: Check Java case sensitivity
Java is case-sensitive, soBy.idmust be lowercase 'id', and parentheses are required.Final Answer:
driver.findElement(By.id("username")); -> Option DQuick Check:
Correct method call syntax = driver.findElement(By.id("username")); [OK]
- Using assignment '=' instead of parentheses
- Wrong capitalization like By.ID or By.Id
- Missing parentheses around the ID string
WebElement button = driver.findElement(By.id("loginBtn"));
button.click();Solution
Step 1: Understand findElement behavior when element missing
If no element matches the ID,findElementthrowsNoSuchElementExceptionimmediately.Step 2: Analyze code flow
The exception occurs at thefindElementline, sobutton.click()is never reached.Final Answer:
Throws NoSuchElementException at findElement line. -> Option AQuick Check:
Missing element causes NoSuchElementException [OK]
- Assuming findElement returns null if element missing
- Expecting NullPointerException instead
- Thinking click() runs even if element not found
WebElement input = driver.findElement(By.id("email"));
input.sendKeys("test@example.com");
WebElement submit = driver.findElement(By.id("submit"));
submit.click();
Assuming the page has no element with ID "submit".Solution
Step 1: Check element existence for each findElement
The element with ID "email" exists, sosendKeysworks fine.Step 2: Analyze finding "submit" element
Since "submit" ID does not exist,findElement(By.id("submit"))throwsNoSuchElementException.Final Answer:
Throws NoSuchElementException at finding "submit" element. -> Option CQuick Check:
Missing ID causes NoSuchElementException [OK]
- Assuming sendKeys fails if element missing later
- Confusing exceptions thrown at different lines
- Expecting click() to throw error instead of findElement
Solution
Step 1: Understand the problem
The button with ID "submitBtn" might not exist, so clicking it directly may cause an exception.Step 2: Evaluate each option
driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); driver.findElement(By.id("submitBtn")).click(); clicks without checking, risking failure. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); WebElement btn = driver.findElement(By.id("submitBtn")); if(btn != null) { btn.click(); } attempts null check but throws NoSuchElementException at findElement since it never returns null. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); try { driver.findElement(By.id("submitBtn")).click(); } catch (NoSuchElementException e) { System.out.println("Button not found, skipping click."); } uses try-catch to handle missing button gracefully. driver.findElement(By.id("userEmail")).sendKeys("user@example.com"); WebElement btn = null; btn.click(); assigns null and calls click(), causing NullPointerException.Final Answer:
Use try-catch to handle missing element and avoid failure. -> Option AQuick Check:
Try-catch handles missing element safely [OK]
- Not handling missing elements causing test failure
- Calling click() on null element
- Assuming findElement returns null if element is missing
Ready to prove it?
Pass the test and this pattern moves unknown
