Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
  • Home
  • /
  • Blog
  • /
  • Locators In Selenium WebDriver With Examples
Selenium TutorialSelenium LocatorsTutorial

Selenium Locators Explained: Types, Examples, Syntax, and Best Practices

Learn different types of locators in Selenium WebDriver and how to use them for Selenium automation testing

Author

Faisal Khatri

May 10, 2026

Selenium locators are used to find and interact with web elements in the DOM, making them a core part of any automation script. They act as the connection between your test script and the user interface, enabling actions like clicking, typing, and validating elements.

However, choosing the right locator is critical. Poor locator strategies can lead to flaky tests, frequent failures, and high maintenance, especially when the DOM structure changes.

In this guide, you’ll learn what Selenium locators are, their different types, syntax, real examples, and best practices to build stable and reliable automation tests.

Key Takeaways

  • Selenium locators are used to identify and interact with elements in the webpage, enabling actions like clicking, typing, and validation in automation scripts.
  • Different locator types such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath are used based on the structure of the web page.
  • Choosing the right locator strategy is critical, as unstable or dynamic locators can lead to flaky tests and frequent failures.
  • ID and CSS Selectors are generally faster and more reliable, while XPath is more flexible for complex element identification.
  • CSS Selectors and XPath allow advanced targeting of elements when basic locators are not sufficient.
  • Writing clean, stable, and readable locators improves test reliability and reduces maintenance effort over time.
  • Understanding how the DOM is structured helps in selecting the most effective locator for each scenario.

What are Locators in Selenium?

Before your Selenium test can click a button, type into a field, or check if something exists on the page, it first needs to find that element. Selenium locators are the methods used to find these elements.

Think of locators as addresses. Just like you need an address to find a house, Selenium needs a locator to find an element on a web page. It looks at things like the element's ID, name, class, or position in the HTML to track it down.

In other words, Selenium locators are like the building blocks of a test script that help testers interact with the elements in the Document Object Model (DOM).

8 Types of Selenium Locators (Quick Sheet)

The table below summarizes the locators in Selenium Java syntax so you can refer back to it whenever you need a quick example.

LocatorsDescriptionSyntax (in Java)
idIdentify the WebElement using the ID attribute.driver.findElement(By.id("IdValue"));
nameIdentify the WebElement using the Name attribute.driver.findElement(By.name("nameValue"));
classNameUse the Class attribute for identifying the object.driver.findElement(By.className("classValue"));
linkTextUse the text in hyperlinks to locate the WebElement.driver.findElement(By.linkText("textofLink"));
partialLinkTextUse a part of the text in hyperlinks to locate the WebElement.driver.findElement(By.partialLinkText("PartialTextofLink"));
tagNameUse the tagName to locate the desired WebElement.driver.findElement(By.tagName("htmlTag"));
cssSelectorUse CSS rules to locate the desired WebElement.driver.findElement(By.cssSelector("cssValue"));
xpathUse XPath to locate the WebElement.driver.findElement(By.xpath("xpathValue"));

Now that you know the essentials of Selenium locators, let me deep-dive into each locator in Selenium WebDriver in more detail.

What Are Selenium Locators Used For?

  • Find and interact with elements: Locate buttons, fields, and other elements to perform actions like clicking, typing, or selecting.
  • Validate UI behavior: Check if elements are present, visible, enabled, or in the expected state.
  • Reduce flaky tests: Using the right locators improves test stability and avoids random failures.
  • Save time and effort: Efficient locators make test scripts easier to write and execute.
  • Improve maintainability: Clean and stable locators make tests easier to read, update, and scale.

Different Types of Locators in Selenium WebDrivber

1. ID Locator in Selenium

ID locator in Selenium is the most preferred and fastest way to locate desired WebElements on the page. ID locators are unique for each element in the DOM.

Since IDs are unique for each element on the page, it is considered the fastest and safest method to locate elements. Unfortunately, developers may or may not follow this rule, as browsers do allow bypassing this rule.

Specifically, in the case of a table or list, the IDs may populate incrementally or dynamically depending on the data in the table. In such cases, testers use other locators in Selenium WebDriver to locate the desired element on the page.

One of the Selenium best practices is to leverage the capabilities offered by the ID locator in Selenium since it is the fastest locator of the entire lot. Therefore, choosing the ID locator over other locators in Selenium WebDriver will go a long way to speed up Selenium test case execution.

I have used the Chrome Developer Tools menu to locate the WebElement using the *id* locator. Below is the DOM structure of the element:

<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

The below method is used for locating the desired element using the *id* locator:

driver.findElement(By.id("input-email"));
Chrome Developer Tools menu

If no DOM element matches the required *id*, *NoSuchElementException* is thrown. Therefore, it is important to have a good know-how of the common exceptions in Selenium to build a more robust Selenium test suite.

2. Name Locator in Selenium

An element can be defined via multiple attributes, one such attribute is Name. A Name locator in Selenium WebDriver can also locate elements like an ID locator.

Unlike ID locators, which are unique for a page, the Name locator may or may not have a unique value. If there are WebElements with the same name, the locator selects the first element with that Name on the page.

In case no such name matches with the defined attribute value, *NoSuchElementException* is raised.

Here is how the desired WebElement can be located using the *name* locator in Selenium:

driver.findElement(By.name("email"));
E-Mail Address field

3. ClassName Locator in Selenium

ClassName locator is used for locating WebElements defined using the class attribute. Below is the DOM snapshot of the Ajax Form Submit page that is available on our website.

Ajax Form Submit DOM

For locating the WebElement of the Submit button via the *className* locator in Selenium, we use the *class* attribute in the following DOM structure:

<input type="button" class="btn btn-dark selenium_btn bg-black text-white hover:bg-lambda-900 py-5 px-10 rounded" name="btn-submit" id="btn-submit" value="submit">

Here is how the desired WebElement was located using the *className* locator in Selenium:

driver.findElement(By.className("btn-dark"));

4. TagName Locator in Selenium

As the name specifies, this CSS locator in Selenium WebDriver is used to identify elements using tag names like *div*, *table*, *h1*, etc.

Notice here that the *findElements* method is used. It will return a list of all the WebElements with the *tagName* "a" that normally holds the links:

driver.findElements(By.tagName("a"));

5. LinkText Locator in Selenium

Elements can be located by LinkText, which is present in the hyperlinks. For example, the first link would be selected in a scenario with multiple links of the same text.

However, this identifier strategy can only be used for elements with an anchor( < a > ) tag.

Below is an example of the TestMu AI Selenium Playground website showcasing the selection of the Ajax Form Submit link that is available on the home page. The DOM below shows the highlighted element:

LambdaTest Selenium Playground

Below is the DOM structure of the same:

<a href="https://www.lambdatest.com/selenium-playground/ajax-form-submit-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Ajax Form Submit</a>

Here is how the desired WebElement was located using the linkText locator in Selenium:

driver.findElement(By.linkText("Ajax Form Submit"));

Below is an example of the TestMu AI Selenium Playground website showcasing the selection of the Ajax Form Submit link that is available on the home page. The DOM below shows the highlighted element:

6. Partial LinkText Locator in Selenium

There is a provision to locate a WebElement using Partial LinkText akin to the normal LinkText locator in Selenium. Locating WebElements using Partial LinkText is preferred when the link text is too long.

Here, the partial text helps identify and use a unique element to perform further actions on it. Sometimes, this can also be locating multiple links on a page with a common partial text.

Here is the DOM structure of the element:

<a href="https://www.lambdatest.com/selenium-playground/auto-healing" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Auto Healing</a>

Here is how the desired WebElement was located using the *partialLinkText* locator in Selenium:

The syntax for locating elements by *partialLinkText* is:

driver.findElement(By.partialLinkText("Healing"));

For more information on Link Text and Partial LinkText locators, we recommend you check this article to find elements with linkText and partialLinkText in Selenium.

Watch this video to learn the *Actions* class in Selenium and how to use it.

7. CSS Selector Locator in Selenium

CSS (Cascading Style Sheets) is used to style web pages. At the same time, CSS is also one of the widely-used ways to locate WebElements in the DOM.

The CSS Selector in Selenium should be chosen when:

  • ID or Name locators are not available
  • You need better performance than XPath
  • You want shorter and more readable expressions

In most automation scenarios, CSS selectors are faster and cleaner than XPath.

1. Tag and ID in CSS Selector

When an element has a unique ID, CSS makes it extremely simple to locate.

Below is the DOM part indicating the First Name field on the Register Account page of the TestMu AI eCommerce Playground website.

Register Account First Name field DOM
<input type="text" name="firstname" value="" placeholder="First Name" id="input-firstname" class="form-control">

Syntax:

tagname#idValue

Example:

driver.findElement(By.cssSelector("input#input-firstname"));

Syntax: css=(Html tag )(\\#) (value of the ID attribute)

2. Tag and Class in CSS Selector

Use a dot (.) to represent class.

Syntax:

tagname.classValue

Example:

driver.findElement(By.cssSelector("input.form-control"));

Here is the DOM snapshot and the corresponding command to access the required WebElement using CSS Selector in Selenium.

Let’s locate the email address field’s element on the TestMu AI eCommerce Playground.

example-DOM-snapshot

3. Tag and Attribute

You can locate elements using any attribute.

Syntax:

tagname[attribute='value']

Example:

driver.findElement(By.cssSelector("input[name='phone']"));

4. Combining Tag, Class, and Attribute

Syntax:

tagname.className[attribute='value']

Example:

driver.findElement(By.cssSelector("button.bg-lambda-900[type='submit']"));

5. Wildcards in CSS Selectors

CSS allows flexible matching using special operators:

Starts With (^)

driver.findElement(By.cssSelector("input[name^='em']"));

Ends With ($)

driver.findElement(By.cssSelector("input[name$='ail']"));

Contains (\\*)

driver.findElement(By.cssSelector("input[class*='control']"));

6. Child Elements in CSS Selector

You can locate nested elements using structural relationships.

Example:

driver.findElement(By.cssSelector("ul > li:nth-child(1) > a"));

Use this when you need elements inside lists, tables, or complex layouts.

8. XPath Using AND and OR

The *AND*, and *OR* operators in the XPath selector in Selenium are used when locating a WebElement based on certain condition sets. In the case of *AND*, both conditions should be true. On the other hand, either of the two conditions can be true for *OR* in operator XPath.

Syntax of OR operator in XPath:

//input[@id='login_1' OR @name='login']

Syntax of AND operator in XPath:

//input[@id='login_1' AND @name='login']
example-DOM-snapshot-2

Below is the DOM structure of the element:

<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

Here is how we used the *OR* operator with the XPath locator in Selenium:

driver.findElement(By.xpath("//input[@id="input-email" or @name="email"]"));

Here is how we used the *AND* operator with the XPath locator in Selenium:

driver.findElement(By.xpath("//input[@id="input-email" AND @name="email"]"));

starts-with() Method in XPath

The *starts-with()* method in XPath offers functionalities similar to the CSS Selector in Selenium. It helps in locating elements that start with a specified attribute value. The *starts-with()* method in XPath is majorly used for locating WebElements whose value changes on the refresh of a page.

Syntax:

//tagname[starts-with(@attribute,'starting name of the attribute value')]

Below is the DOM structure of the element:

<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control">
Account Login Password field

Here is how we locate the Password element using the *starts-with()* method with *xpath* in Selenium:

driver.findElement(By.xpath("//input[starts-with(@name,'pass')]"));

XPath Text

Text in the XPath locator in Selenium helps locate WebElements via XPath using exact text match. It can be used when elements have to be located by looking into the tags containing certain text.

Syntax:

//div[text()='Logged In']

Here is the DOM structure of the required WebElement: <button type="submit" class="bg-black hover:bg-transparent hover:text-black border border-black text-white rounded focus:outline-none selenium\\_btn py-5 px-10 rounded mt-20 w-120">Submit\\</button>

Here is how we locate the Submit button element using the *xpath* text:

driver.findElement(By.xpath("//button[text()='Submit']"));

Both CSS selectors and XPath are helpful when running complex Selenium test automation scenarios. The choice between XPath and CSS Selector purely depends on the scenario complexity and your convenience in locating WebElements using the corresponding locator.

Relative Locators in Selenium 4

Selenium 4 introduced Relative Locators, which allow you to locate elements based on their position relative to other elements on the page. The relative locators in Selenium 4 are particularly useful when elements do not have unique IDs, names, or stable attributes.

Instead of locating an element directly, you can tell Selenium to find an element above, below, near, left, or right of another element.

Relative locators make test scripts easier to read and more stable when working with dynamic UI layouts.

Types of Relative Locators

Selenium provides the following relative locator methods:

  • above() -> Finds element above another element
  • below() -> Finds element below another element
  • toLeftOf() -> Finds element to the left of another element
  • toRightOf() -> Finds element to the right of another element
  • near() -> Finds element near another element (within ~50px)

Example (Java)

WebElement password = driver.findElement(By.id("password"));
WebElement username = driver.findElement(with(By.tagName("input")).above(password));

In this example, Selenium finds the username field by locating the input element above the password field.

Relative locators are useful when:

  • IDs are dynamic
  • XPath becomes too long
  • Page layout changes frequently
  • You want more readable test code

6 Best Practices for Using Locators in Selenium

Choosing the right locator is important for creating stable, fast, and maintainable test scripts. Poor locator choices often lead to flaky tests that fail when the UI changes.

Follow these best practices when working with Selenium locators.

For teams whose locators still break on every release despite following these patterns, Selenium AI covers self-healing locator strategies, AI-assisted XPath generation, and how MCP-based agents can automatically repair broken selectors as the DOM changes between builds.

1. Prefer ID Whenever Available

ID is the fastest and most reliable locator because it is usually unique.

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

Avoid using complex XPath when ID is available.

2. Avoid Dynamic Attributes

Do not use attributes that change every time the page loads.

Bad example:

id="user_45892"

Good example:

name="username"

Dynamic values make tests unstable.

3. Keep XPath and CSS Short

Very long locators break easily when UI changes.

Bad:

/html/body/div[2]/div/div/form/input

Better:

input[name='email']

Short locators are easier to maintain.

4. Use CSS Selector When Possible

CSS selectors are usually faster than XPath and easier to read.

Use CSS when:

  • ID is not available
  • Class or attribute is available
  • XPath becomes complex

Example:

driver.findElement(By.cssSelector("input[type='email']"));

5. Use XPath Only When Needed

XPath is powerful but should not be the first choice.

Use XPath when:

  • Element has no ID or Name
  • Element depends on hierarchy
  • Element depends on text

Example:

driver.findElement(By.xpath("//button[text()='Login']"));

6. Use Explicit Waits with Locators

Sometimes elements take time to appear.

Use waits to avoid test failures.

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

This makes tests more reliable.

When to Use Each Locator in Selenium

Different locators are useful in different situations. Choosing the correct one improves test stability and performance.

LocatorWhen to Use
IDFirst choice, fastest and unique
NameWhen ID is not available
ClassNameWhen class is unique
TagNameWhen working with groups of elements
LinkTextFor links with visible text
PartialLinkTextWhen link text is long
CSS SelectorFlexible and fast
XPathComplex elements
Relative LocatorsWhen layout-based locating is needed

Use the simplest locator that uniquely identifies the element.

4 Common Mistakes to Avoid with Selenium Locators

Many test failures happen because of a poor locator strategy.

Here are common mistakes to avoid.

1. Using Absolute XPath

Absolute XPath breaks when page structure changes.

Bad:

/html/body/div/div/div/input

Use relative XPath instead.

2. Using Auto-Generated IDs

Dynamic IDs change every run.

Avoid:

id="input_12345"

Use stable attributes.

3. Using Very Long CSS or XPath

Long locators are hard to maintain.

Keep them short and readable.

4. Not Waiting for Elements

Tests fail when elements are not loaded yet.

Always use waits when needed.

Final Words: Which Is the Most Effective Locator in Selenium?

There isn’t a single “best” locator that works in every situation. The most effective locator depends on how the elements are structured in the application. That said, ID is generally the most reliable choice when available.

Why ID is usually the best option?

  • Uniqueness: IDs are meant to be unique on a page, which makes element identification precise and unambiguous.
  • Performance: Locating elements by ID is typically the fastest, as browsers can directly access them without scanning large parts of the DOM.
  • Stability: Well-defined IDs tend to change less frequently than other attributes, making tests more stable over time.

What to Use When ID Is Not Available?

IDs are not always present or reliable, so other locators are often needed.

  • CSS Selector: Fast and flexible, ideal for targeting elements using classes or attributes.
    Best for: Clean and reliable selectors when IDs are missing.
  • XPath: More powerful, useful for locating elements in complex or dynamic DOM structures.
    Best for: Advanced cases, but can be slower and harder to maintain.

Author

Mohammad Faisal Khatri is a Software Testing Professional with 17+ years of experience in manual exploratory and automation testing. He currently works as a Senior Testing Specialist at Kafaat Business Solutions and has previously worked with Thoughtworks, HCL Technologies, and CrossAsyst Infotech. He is skilled in tools like Selenium WebDriver, Rest Assured, SuperTest, Playwright, WebDriverIO, Appium, Postman, Docker, Jenkins, GitHub Actions, TestNG, and MySQL. Faisal has led QA teams of 5+ members, managing delivery across onshore and offshore models. He holds a B.Com degree and is ISTQB Foundation Level certified. A passionate content creator, he has authored 100+ blogs on Medium, 40+ on TestMu AI, and built a community of 25K+ followers on LinkedIn. His GitHub repository “Awesome Learning” has earned 1K+ stars.

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

Frequently asked questions

Did you find this page helpful?

More Related Hubs

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