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.