We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Use the most basic and reliable locators in Selenium WebDriver.
In this lesson, you’ll practice using the two simplest and most common Selenium locators:
By.id("...")By.name("...")These are usually your first choice because:
What it does
Finds the element whose id attribute exactly matches the value you pass.
Example: By.id("lname") → element with id="lname".
When to use it
id.By.id over other strategies when possible. Avoid using IDs that look auto-generated or dynamic (e.g. input-123, react-xyz).What it does
Finds the element whose name attribute matches the value you pass.
Example: By.name("newsletter") → element with name="newsletter".
When to use it
id, but the element has a meaningful name.By.name as your second choice after By.id. Watch out for multiple elements sharing the same name (e.g. radio buttons).Interact with the form directly to see how Selenium would locate these elements!
12345678WebElement lastNameInput = driver.findElement(By.id("lname"));
lastNameInput.clear();
lastNameInput.sendKeys("Doe");
WebElement newsletterCheckbox = driver.findElement(By.name("newsletter"));
newsletterCheckbox.click();
driver.quit();id="lname" and returns it as a WebElement."Doe" into the last name input, simulating real keyboard input.name="newsletter" attribute and returns it as a WebElement.Always try By.id first. If there’s no good id, fall back to By.name before jumping to more complex locators.
Make sure the id or name doesn’t change on refresh or between environments (dev, test, prod). Stable attributes → stable tests.
Use locators that tell a story (By.id("lastName"), By.name("newsletter")) so your tests are easy to understand and maintain.