World’s largest virtual agentic engineering & quality conference

WHENAUG 19-21
WHEREVirtual · Global
Register Now
Testing

Selenium Locators Tutorial: A Comprehensive Guide, with Examples & Best Practices

Here's a perfect guide on Selenium Locators to help you understand what are Selenium Locators & its different types. There's a ton of content here to help you learn everything about locators in Selenium.

Author

Ritesh Shetty

Author

Last Updated on: July 16, 2026

Locators in Selenium play an important role in the life of an automation engineer. They provide a path to access web elements that are essential to automate specific actions like click, type, checkboxes, etc.

Web Element Locators Explained By Louise J Gibbs

By Louise J Gibbs

In this tutorial, you will learn about locators in Selenium and their types, deep dive into different locators and their use cases, and learn using locators with different automation testing frameworks.

A Selenium locator is the query strategy that tells the WebDriver how to find an element on a page. It is the instruction, expressed through the By class, that describes where an element lives in the DOM. Every locator you write, whether by id, name, CSS Selector, or XPath, is simply a different way of answering the same question: which element on this page do I want?

It is important to separate two ideas that beginners often confuse. A locator is the strategy, for example By.id("username"). A WebElement is the object Selenium hands back once that strategy successfully matches an element. You call driver.findElement(locator) with a locator, and you receive a WebElement in return. The locator is the recipe, and the WebElement is the dish you then act on with click(), sendKeys(), or getText().

The 8 Traditional Selenium Locators

Selenium WebDriver ships with eight built-in locator strategies, all exposed through the By class. The examples below use Java and reference elements you can practice on in the TestMu AI Selenium Playground. Pick one language and stay consistent across your suite.

1. ID Locator

The ID locator finds an element by its unique id attribute and is the fastest, most reliable strategy available.

WebElement user = driver.findElement(By.id("user-message"));
user.sendKeys("TestMu AI");

2. Name Locator

The Name locator matches an element by its name attribute, which is handy for form fields.

WebElement email = driver.findElement(By.name("name"));
email.sendKeys("qa@example.com");

3. Class Name Locator

The Class Name locator selects an element by a single CSS class value applied to it.

WebElement button = driver.findElement(By.className("selenium_btn"));
button.click();

4. Tag Name Locator

The Tag Name locator returns elements by their HTML tag, which is useful for grabbing every link or list item.

List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());

5. Link Text Locator

The Link Text locator matches an anchor by the exact visible text of the link.

WebElement link = driver.findElement(By.linkText("Selenium Playground"));
link.click();

6. Partial Link Text Locator

The Partial Link Text locator matches an anchor when only part of its visible text is known.

WebElement link = driver.findElement(By.partialLinkText("Playground"));
link.click();

7. CSS Selector

The CSS Selector locator uses standard CSS syntax and is fast and expressive for complex matches.

WebElement submit = driver.findElement(By.cssSelector("input#submit.btn"));
submit.click();

8. XPath Locator

The XPath locator navigates the DOM tree and can match on text, attributes, and relationships that other locators cannot.

WebElement heading = driver.findElement(By.xpath("//h1[text()='Selenium Playground']"));
System.out.println(heading.getText());

Selenium Locators Comparison Table

The table below summarizes all eight locators so you can pick the right one at a glance based on relative speed and typical use case.

LocatorExampleSpeedBest Use Case
IDBy.id("user-message")FastestElements with a unique id
NameBy.name("name")FastForm fields with a name attribute
Class NameBy.className("selenium_btn")FastGrouped elements sharing a class
Tag NameBy.tagName("a")MediumCollecting all elements of a type
Link TextBy.linkText("Selenium Playground")MediumAnchors with exact visible text
Partial Link TextBy.partialLinkText("Playground")MediumAnchors with dynamic partial text
CSS SelectorBy.cssSelector("input#submit")FastComplex matches without an id
XPathBy.xpath("//h1[text()='...']")SlowestDynamic elements, text and axes

Relative Locators in Selenium 4 (Friendly Locators)

Selenium 4 introduced relative locators, also called friendly locators, which let you find an element by its visual position relative to a known reference element. Instead of writing a brittle XPath, you describe the layout the way a human would: the field above the password box, the button to the right of the label. Import them with import static org.openqa.selenium.support.locators.RelativeLocator.with;.

The five methods are above(), below(), toLeftOf(), toRightOf(), and near().

WebElement password = driver.findElement(By.id("password"));

// The field directly above the password field
WebElement email = driver.findElement(with(By.tagName("input")).above(password));

// The label below the password field
WebElement hint = driver.findElement(with(By.tagName("label")).below(password));

// The button to the right of the submit label
WebElement submit = driver.findElement(with(By.tagName("button")).toRightOf(By.id("submit-label")));

// Any input within 50px of the reference element
WebElement nearby = driver.findElement(with(By.tagName("input")).near(password));

You can chain methods to pin down an element that sits at the intersection of two directions.

// The cell that is both below the header and to the right of the name column
WebElement cell = driver.findElement(
        with(By.tagName("td"))
            .below(By.id("table-header"))
            .toRightOf(By.id("name-column")));
cell.click();

Advanced Locator Classes: ByChained and ByAll

Beyond the standard By strategies, the Selenium support library offers ByChained and ByAll for composing locators. Import them from org.openqa.selenium.support.pagefactory.

ByChained

ByChained applies locators in sequence to find a nested element: the first locator finds the parent, and the next searches only within it.

// Find the input that lives inside the login form
WebElement field = driver.findElement(
        new ByChained(By.id("login-form"), By.name("username")));
field.sendKeys("TestMu AI");

ByAll

ByAll matches an element that satisfies any one of several locators, which is useful when the same control appears under different attributes across pages.

// Match the submit control whether it uses an id or a name
WebElement submit = driver.findElement(
        new ByAll(By.id("submit"), By.name("submit-btn")));
submit.click();

Which Selenium Locator Is Best? (Performance and Reliability)

There is a clear hierarchy for choosing a locator, driven by speed and stability. Follow this order and your tests will be both faster and less flaky.

  • ID: Always prefer ID when an element has a unique, stable id. The browser resolves it directly, so it is the fastest and least fragile choice.
  • Name and CSS Selectors: When there is no id, fall back to Name for simple form fields and CSS Selectors for anything more complex. CSS runs on the browser's native, highly optimized engine, so it stays fast.
  • XPath as a last resort: Reach for XPath only when you must match on text, traverse axes, or locate elements no other strategy can reach. XPath is evaluated by the WebDriver rather than the browser, which makes it slower, and long absolute paths break the moment the DOM shifts.

The practical takeaway is to keep locators as specific and as shallow as possible. Ask developers to add stable id or data-testid attributes to key elements so your suite does not depend on fragile positional paths.

Absolute vs Relative XPath

XPath comes in two forms. Absolute XPath starts from the root of the document with a single slash and traces the complete path to the element. It is precise but brittle, because any change in the page structure breaks it.

// Absolute XPath: full path from the root
WebElement el = driver.findElement(By.xpath("/html/body/div[2]/form/input[1]"));

Relative XPath starts with a double slash and matches from anywhere in the DOM. It is shorter, more readable, and far more resilient to layout changes, which is why teams use it almost exclusively.

// Relative XPath: match from anywhere by attribute
WebElement el = driver.findElement(By.xpath("//input[@name='username']"));
Run tests up to 70% faster on the TestMu AI cloud grid

Author

...

Ritesh Shetty

Blogs: 7

  • Twitter
  • Linkedin

Ritesh Shetty is a Community Contributor with experience in building and sharing content around software testing, automation, and technology. A former Content Marketing Manager at TestMu AI, he has contributed to simplifying testing concepts for QA engineers and developers. Currently serving as Head of Growth at Arya.ai, Ritesh continues to connect product, engineering, and quality through impactful knowledge-sharing and community contributions.

Open in ChatGPT Icon

Open in ChatGPT

Open in Claude Icon

Open in Claude

Open in Perplexity Icon

Open in Perplexity

Open in Grok Icon

Open in Grok

Open in Gemini AI Icon

Open in Gemini AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free
...
TestMu Conf 2026

World's largest virtual agentic engineering & quality conference

...

AUG 19-21, 2026

REGISTER NOW

Frequently asked questions

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests