How to Locate Elements Using By.id() in Selenium WebDriver

Selenium is a powerful tool used for automating web applications for testing purposes. One of the most basic and commonly used techniques in Selenium is locating web elements by their HTML id attribute.

✅ What is the id Attribute?

In HTML, the id attribute is used to uniquely identify elements on a web page.

<input type="text" id="username" />

Each id value must be unique within a single HTML page, which makes it a reliable way to locate elements.

✅ Why Use By.id() in Selenium?

🛠 How to Locate Elements Using By.id() in Java

👉 Syntax

driver.findElement(By.id("element_id"));

Here:

💻 Example: Login Form Automation

🔹 HTML of the Form

<form>
  <input type="text" id="username" name="username" />
  <input type="password" id="password" name="password" />
  <button id="loginBtn">Login</button>
</form>

🔹 Java + Selenium Code

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTest {
    public static void main(String[] args) {
        // Set path to ChromeDriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Launch browser
        WebDriver driver = new ChromeDriver();

        // Open login page
        driver.get("https://example.com/login");

        // Locate elements by id
        WebElement usernameField = driver.findElement(By.id("username"));
        WebElement passwordField = driver.findElement(By.id("password"));
        WebElement loginButton = driver.findElement(By.id("loginBtn"));

        // Interact with the elements
        usernameField.sendKeys("myUsername");
        passwordField.sendKeys("myPassword");
        loginButton.click();

        // Close the browser
        driver.quit();
    }
}

✅ Best Practices

Practice Description
Use By.id() Prefer IDs over other locators like xpath or cssSelector when available
Check for uniqueness Ensure the id used is unique on the page
Use WebDriverWait If the element loads dynamically, use explicit wait

🔹 Example with Wait

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn")));

🧩 Common Issues and Troubleshooting

Issue Solution
NoSuchElementException Check if the id exists and is visible
Dynamic IDs Use other strategies like By.name() or By.xpath() if the id changes
Page not loaded Use waits before locating elements

📌 Summary

  • The By.id() locator is fast, reliable, and beginner-friendly.
  • Ideal for automating forms, buttons, and static web pages.
  • Always verify the uniqueness of id before using.
  • Combine with waits for better reliability in real-world web apps.

🚀 What’s Next?

Now that you’ve learned how to use By.id() in Selenium with Java, try exploring other locators like:

🤖
PrepCampusPlus AI Tutor
Scroll to Top