Class Name Locator in Selenium
The Class Name Locator is one of the standard locator strategies provided by Selenium WebDriver for identifying web elements using the value of their HTML class attribute. It is useful when an element does not have a suitable unique ID or when multiple elements belong to the same CSS class.
In Selenium Java, the Class Name Locator is implemented using By.className(). For example, if an HTML element contains class="username", Selenium can locate it using driver.findElement(By.className("username")).
Locators are an important part of Selenium WebDriver because Selenium must identify the correct WebElement before performing actions such as click(), sendKeys(), clear(), getText(), and attribute validation. JustAcademy's Selenium training curriculum includes different locator strategies such as ID, Name, Class Name, XPath, and CSS Selectors for locating and interacting with web elements. :contentReference[oaicite:0]{index=0}
Learn more through the JustAcademy's Selenium Training Course and explore the Selenium Course Demo Registration.
1. What is a Class Name Locator?
A Class Name Locator identifies a web element by using the value of its HTML class attribute.
The basic Selenium Java syntax is:
driver.findElement(By.className("classValue"));
For example:
<input type="text" class="username">
The element can be located using:
driver.findElement(By.className("username"));
2. Understanding the HTML Class Attribute
The class attribute is commonly used in HTML for applying CSS styles, grouping related elements, and identifying elements that share a common design or behavior.
Example:
<input type="text" class="form-control">
Here, form-control is the value of the class attribute.
Selenium can use this value with:
By.className("form-control")
3. Syntax of Class Name Locator
The Selenium Java syntax is:
By.className("classValue")
With findElement():
WebElement element = driver.findElement(By.className("classValue"));
Example:
WebElement username = driver.findElement(By.className("username"));
4. Simple Class Name Example
Consider the following HTML:
<input type="text" class="username">
Selenium code:
driver.findElement(By.className("username")).sendKeys("admin");
Selenium searches the page for an element whose class attribute contains the specified class token.
5. Class Name Locator with Username Field
<input type="text" class="username" placeholder="Enter Username">
driver.findElement(By.className("username")).sendKeys("admin");
6. Class Name Locator with Password Field
<input type="password" class="password" placeholder="Enter Password">
driver.findElement(By.className("password")).sendKeys("admin123");
7. Class Name Locator with Email Field
<input type="email" class="email-field">
driver.findElement(By.className("email-field")).sendKeys("[email protected]");
8. Class Name Locator with Search Box
<input type="search" class="search-box">
driver.findElement(By.className("search-box")).sendKeys("Selenium WebDriver");
9. Class Name Locator with Button
<button type="submit" class="login-button">Login</button>
Selenium:
driver.findElement(By.className("login-button")).click();
10. Class Name Locator with Checkbox
<input type="checkbox" class="terms-checkbox">
WebElement terms = driver.findElement(By.className("terms-checkbox"));
if (!terms.isSelected()) {
terms.click();
}
11. Class Name Locator with Radio Button
<input type="radio" class="gender-option" value="male">
<input type="radio" class="gender-option" value="female">
If multiple elements use the same class, use findElements():
List<WebElement> genderOptions =
driver.findElements(By.className("gender-option"));
12. Class Name Locator with Form Fields
<form>
<input type="text" class="first-name">
<input type="text" class="last-name">
<input type="email" class="email-field">
<input type="password" class="password-field">
</form>
Selenium:
driver.findElement(By.className("first-name")).sendKeys("John");
driver.findElement(By.className("last-name")).sendKeys("Smith");
driver.findElement(By.className("email-field")).sendKeys("[email protected]");
driver.findElement(By.className("password-field")).sendKeys("Pass@123");
13. Class Name Locator with sendKeys()
The sendKeys() method is used to enter text into input elements.
driver.findElement(By.className("username")).sendKeys("admin");
14. Class Name Locator with clear()
The clear() method removes existing text from a text field.
WebElement username =
driver.findElement(By.className("username"));
username.clear();
username.sendKeys("newUser");
15. Class Name Locator with click()
The click() method can be used on buttons, checkboxes, radio buttons, links, and other clickable elements.
driver.findElement(By.className("login-button")).click();
16. Class Name Locator with getText()
The getText() method retrieves visible text from an element.
String message =
driver.findElement(By.className("success-message")).getText();
System.out.println(message);
17. Class Name Locator with getAttribute()
The getAttribute() method can be used to retrieve an HTML attribute.
WebElement username =
driver.findElement(By.className("username"));
String value = username.getAttribute("value");
System.out.println(value);
18. Class Name Locator with WebElement
The located element can be stored in a WebElement variable.
WebElement emailField =
driver.findElement(By.className("email-field"));
emailField.sendKeys("[email protected]");
19. Required Selenium Imports
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
20. Complete Basic Class Name Program
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClassNameLocatorExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(By.className("username"))
.sendKeys("admin");
driver.findElement(By.className("password"))
.sendKeys("admin123");
driver.findElement(By.className("login-button"))
.click();
driver.quit();
}
}
21. Class Name Locator in Login Form
Consider the following login form:
<form>
<input type="text" class="username">
<input type="password" class="password">
<button type="submit" class="login-button">Login</button>
</form>
Selenium automation:
driver.findElement(By.className("username"))
.sendKeys("admin");
driver.findElement(By.className("password"))
.sendKeys("admin123");
driver.findElement(By.className("login-button"))
.click();
22. Class Name Locator in Registration Form
<input type="text" class="first-name">
<input type="text" class="last-name">
<input type="email" class="email-field">
<input type="password" class="password-field">
<input type="password" class="confirm-password">
<button type="submit" class="register-button">Register</button>
Selenium:
driver.findElement(By.className("first-name"))
.sendKeys("John");
driver.findElement(By.className("last-name"))
.sendKeys("Smith");
driver.findElement(By.className("email-field"))
.sendKeys("[email protected]");
driver.findElement(By.className("password-field"))
.sendKeys("Pass@123");
driver.findElement(By.className("confirm-password"))
.sendKeys("Pass@123");
driver.findElement(By.className("register-button"))
.click();
23. Class Name Locator in Search Form
<input type="text" class="search-input">
<button type="submit" class="search-button">Search</button>
driver.findElement(By.className("search-input"))
.sendKeys("Laptop");
driver.findElement(By.className("search-button"))
.click();
24. What is a Class Token?
An HTML element can contain multiple class names separated by spaces.
<input class="form-control input-field username">
Here, the element has three class tokens:
form-control
input-field
username
Each token represents an individual class name.
25. Important Rule: Do Not Pass Multiple Classes to By.className()
One of the most common mistakes is trying to pass the complete class attribute containing spaces to By.className().
For example:
<input class="form-control username">
This is incorrect:
driver.findElement(
By.className("form-control username")
);
By.className() expects a single class name token, not a space-separated list of multiple classes.
26. Correct Way to Use By.className()
For:
<input class="form-control username">
You can use one class token:
driver.findElement(By.className("form-control"));
or:
driver.findElement(By.className("username"));
If one class is not sufficiently specific, use a CSS Selector instead.
27. Using CSS Selector for Multiple Classes
Suppose the element is:
<input class="form-control username">
A CSS Selector can target both classes:
driver.findElement(
By.cssSelector(".form-control.username")
);
This is different from By.className(), which accepts one class token.
28. Class Name Locator with findElement()
findElement() returns the first matching WebElement.
WebElement username =
driver.findElement(By.className("username"));
If Selenium cannot find a matching element in the current browsing context, it can throw NoSuchElementException.
29. Class Name Locator with findElements()
findElements() returns a list of matching WebElements.
List<WebElement> elements =
driver.findElements(By.className("username"));
If no matching elements are found, an empty list is returned.
30. Difference Between findElement() and findElements()
| Feature | findElement() | findElements() |
| Return Type | WebElement | List<WebElement> |
| Multiple Matches | Returns first matching element | Returns all matching elements |
| No Match | Throws NoSuchElementException | Returns empty list |
| Typical Use | Single target | Groups of elements |
31. Class Name Locator with Multiple Elements
Suppose a page contains:
<button class="product-button">Product 1</button>
<button class="product-button">Product 2</button>
<button class="product-button">Product 3</button>
Using findElement():
WebElement button =
driver.findElement(By.className("product-button"));
The first matching element is returned.
Using findElements():
List<WebElement> buttons =
driver.findElements(By.className("product-button"));
All matching elements are returned.
32. Counting Elements Using Class Name
List<WebElement> buttons =
driver.findElements(By.className("product-button"));
System.out.println("Number of buttons: " + buttons.size());
This is useful for verifying repeated components on a page.
33. Class Name Locator for Multiple Buttons
<button class="action-button">Edit</button>
<button class="action-button">Delete</button>
<button class="action-button">View</button>
List<WebElement> buttons =
driver.findElements(By.className("action-button"));
for (WebElement button : buttons) {
System.out.println(button.getText());
}
34. Class Name Locator for Checkbox Groups
<input type="checkbox" class="skill">
<input type="checkbox" class="skill">
<input type="checkbox" class="skill">
List<WebElement> skills =
driver.findElements(By.className("skill"));
35. Selecting Multiple Checkboxes
List<WebElement> skills =
driver.findElements(By.className("skill"));
for (WebElement skill : skills) {
if (!skill.isSelected()) {
skill.click();
}
}
36. Class Name Locator for Radio Buttons
<input type="radio" class="gender-option" value="male">
<input type="radio" class="gender-option" value="female">
Locate all options:
List<WebElement> options =
driver.findElements(By.className("gender-option"));
37. Selecting a Specific Radio Button by Value
List<WebElement> options =
driver.findElements(By.className("gender-option"));
for (WebElement option : options) {
if ("female".equals(option.getAttribute("value"))) {
option.click();
break;
}
}
38. Class Name Locator with isSelected()
The isSelected() method is useful for radio buttons and checkboxes.
WebElement checkbox =
driver.findElement(By.className("terms-checkbox"));
if (!checkbox.isSelected()) {
checkbox.click();
}
39. Class Name Locator with isDisplayed()
WebElement message =
driver.findElement(By.className("success-message"));
if (message.isDisplayed()) {
System.out.println("Message is displayed.");
}
40. Class Name Locator with isEnabled()
WebElement submit =
driver.findElement(By.className("submit-button"));
if (submit.isEnabled()) {
System.out.println("Submit button is enabled.");
}
41. Complete State Validation
WebElement element =
driver.findElement(By.className("submit-button"));
System.out.println("Displayed: " + element.isDisplayed());
System.out.println("Enabled: " + element.isEnabled());
System.out.println("Selected: " + element.isSelected());
42. Class Name Locator with Explicit Wait
When an element loads dynamically, use an explicit wait.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.className("username")
)
);
username.sendKeys("admin");
43. Class Name Locator with ElementToBeClickable
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(
ExpectedConditions.elementToBeClickable(
By.className("login-button")
)
);
loginButton.click();
44. Required Wait Imports
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
45. Class Name Locator and Dynamic Elements
Modern web applications often create elements dynamically using JavaScript. The class attribute may be added after page loading.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement search = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.className("search-box")
)
);
search.sendKeys("Selenium");
46. Class Name Locator and AJAX
If an AJAX operation adds a new element to the page, the test should wait for the expected condition rather than immediately attempting interaction.
WebElement result = new WebDriverWait(
driver,
Duration.ofSeconds(10)
).until(
ExpectedConditions.visibilityOfElementLocated(
By.className("search-result")
)
);
System.out.println(result.getText());
47. Class Name Locator and Iframes
If an element is inside an iframe, switch to the iframe before using the Class Name Locator.
WebElement frame =
driver.findElement(By.id("loginFrame"));
driver.switchTo().frame(frame);
driver.findElement(By.className("username"))
.sendKeys("admin");
driver.switchTo().defaultContent();
48. Class Name Locator and Multiple Windows
If the target element is in another browser window or tab, switch to the appropriate window before locating it.
String originalWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(originalWindow)) {
driver.switchTo().window(window);
break;
}
}
driver.findElement(By.className("username"))
.sendKeys("admin");
49. Class Name Locator and Shadow DOM
Elements inside a Shadow DOM may require Shadow Root handling. A normal locator from the document context may not directly cross a shadow boundary.
The appropriate Selenium Shadow DOM APIs should be used when the target element belongs to a shadow tree.
50. Class Name Locator with Dropdown
A standard select element can have a class attribute.
<select class="country-select">
<option value="india">India</option>
<option value="usa">USA</option>
</select>
Locate it:
WebElement country =
driver.findElement(By.className("country-select"));
Use Selenium's Select class:
Select select = new Select(country);
select.selectByValue("india");
51. Import for Select
import org.openqa.selenium.support.ui.Select;
52. Class Name Locator for Textarea
<textarea class="address-field"></textarea>
driver.findElement(By.className("address-field"))
.sendKeys("Mumbai, Maharashtra");
53. Class Name Locator for File Upload
<input type="file" class="resume-upload">
driver.findElement(By.className("resume-upload"))
.sendKeys("C:\\files\\resume.pdf");
54. Class Name Locator for Error Messages
<span class="error-message">Invalid email</span>
String error =
driver.findElement(By.className("error-message"))
.getText();
System.out.println(error);
55. Class Name Locator for Success Messages
<div class="success-message">
Registration successful
</div>
String message =
driver.findElement(By.className("success-message"))
.getText();
System.out.println(message);
56. Class Name Locator vs ID Locator
| Feature | ID Locator | Class Name Locator |
| Java Method | By.id() | By.className() |
| HTML Attribute | id | class |
| Typical Purpose | Unique identification | Grouping/styling/identification |
| Can Be Shared | IDs are intended to be unique | Classes are commonly shared |
| Multiple Matches | Usually unexpected | Very common |
57. Class Name Locator vs Name Locator
| Feature | Class Name | Name |
| HTML Attribute | class | name |
| Selenium Method | By.className() | By.name() |
| Common Usage | Styling and element grouping | Form controls |
| Shared Values | Very common | Also possible |
58. Class Name Locator vs Tag Name
| Feature | Class Name | Tag Name |
| Selenium Method | By.className() | By.tagName() |
| Uses | class attribute | HTML element name |
| Example | username | input |
59. Class Name Locator vs XPath
| Feature | Class Name | XPath |
| Syntax | By.className("username") | By.xpath("//input[@class='username']") |
| Complexity | Simple | Simple to advanced |
| Text Matching | No direct support | Supported |
| Element Relationships | No | Yes |
| Multiple Conditions | Limited | Supported |
60. Class Name Locator vs CSS Selector
CSS Selectors provide more flexibility when working with multiple classes or combining classes with other attributes.
For example:
<input class="form-control username">
Single class:
driver.findElement(By.className("username"));
Multiple classes:
driver.findElement(
By.cssSelector(".form-control.username")
);
61. Class Name Locator and CSS Class Names with Spaces
Consider:
<button class="btn btn-primary login-button">Login</button>
The class attribute contains three class tokens:
btn
btn-primary
login-button
You can use:
By.className("btn")
or:
By.className("btn-primary")
or:
By.className("login-button")
But do not use:
By.className("btn btn-primary")
62. Class Name Locator with CSS Selector for Multiple Classes
For an element with:
class="btn btn-primary login-button"
CSS can combine class selectors:
By.cssSelector(".btn.btn-primary.login-button")
63. Class Name Locator and Dynamic Classes
Some frameworks generate dynamic class names.
<input class="input-48291">
The class might later become:
<input class="input-73192">
A locator based on the complete dynamic class may become unreliable.
64. Handling Dynamic Class Names
When the class changes dynamically, inspect the element for a stable identifier.
<input id="username" class="input-48291">
If the ID is stable, use:
By.id("username")
Alternatively, a stable CSS or XPath locator can be considered.
65. Class Name Locator and Framework-Generated Classes
Modern frameworks can generate classes for styling, state, component libraries, or CSS modules. Some generated classes may change between builds.
For maintainable automation, avoid depending on classes that are clearly generated, hashed, or frequently changing unless the application team intentionally treats them as stable test hooks.
66. Class Name Locator in Page Object Model
Class Name Locators can be stored inside Page Object classes.
public class LoginPage {
private WebDriver driver;
private By username =
By.className("username");
private By password =
By.className("password");
private By loginButton =
By.className("login-button");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String user, String pass) {
driver.findElement(username)
.sendKeys(user);
driver.findElement(password)
.sendKeys(pass);
driver.findElement(loginButton)
.click();
}
}
67. Benefits of Class Name Locator in POM
- Locators are centralized.
- Page classes are easier to maintain.
- Test methods become cleaner.
- Locator changes can be made in one location.
- Common page elements can be reused.
- Automation code becomes more readable.
68. Class Name Locator with TestNG
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void loginTest() {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(By.className("username"))
.sendKeys("admin");
driver.findElement(By.className("password"))
.sendKeys("admin123");
driver.findElement(By.className("login-button"))
.click();
driver.quit();
}
}
69. Class Name Locator with TestNG Assertion
import org.testng.Assert;
WebElement message =
driver.findElement(By.className("success-message"));
Assert.assertTrue(message.isDisplayed());
70. Class Name Locator with Text Validation
String actualMessage =
driver.findElement(
By.className("success-message")
).getText();
Assert.assertEquals(
actualMessage,
"Registration successful"
);
71. Reusable Class Name Utility
public void enterText(By locator, String text) {
WebElement element =
driver.findElement(locator);
element.clear();
element.sendKeys(text);
}
Usage:
enterText(By.className("username"), "admin");
enterText(By.className("email-field"), "[email protected]");
72. Reusable Click Utility
public void click(By locator) {
driver.findElement(locator).click();
}
Usage:
click(By.className("login-button"));
click(By.className("submit-button"));
73. Explicit Wait Utility for Class Name
public WebElement waitForElement(By locator) {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
return wait.until(
ExpectedConditions.visibilityOfElementLocated(locator)
);
}
Usage:
WebElement username =
waitForElement(By.className("username"));
username.sendKeys("admin");
74. Common Exceptions with Class Name Locator
| Exception | Possible Cause |
| NoSuchElementException | Incorrect class or element not available |
| InvalidSelectorException | Invalid locator syntax or unsupported class input |
| ElementNotInteractableException | Element exists but is not interactable |
| ElementClickInterceptedException | Another element blocks the target |
| StaleElementReferenceException | DOM changed after the element was located |
| TimeoutException | Expected wait condition was not satisfied |
75. NoSuchElementException with Class Name
Example:
driver.findElement(
By.className("wrong-class")
).click();
If the class does not match any element in the current browsing context, Selenium can throw NoSuchElementException.
Check:
- The class spelling.
- Whether the class is present.
- Whether the element has loaded.
- Whether the element is inside an iframe.
- Whether the class is dynamically generated.
76. ElementNotInteractableException
An element may exist in the DOM but may not be ready for interaction.
driver.findElement(By.className("username"))
.sendKeys("admin");
Possible causes include hidden elements, disabled controls, overlays, or an incorrect page state.
77. ElementClickInterceptedException
This can occur when another element is covering the target.
driver.findElement(By.className("submit-button"))
.click();
Possible causes include:
- Popup overlays.
- Modal dialogs.
- Loading screens.
- Sticky headers.
- Animations.
78. StaleElementReferenceException
A WebElement reference can become stale when the DOM is refreshed or rebuilt.
WebElement username =
driver.findElement(By.className("username"));
driver.navigate().refresh();
username.sendKeys("admin");
After the refresh, the old reference may no longer represent the current element. Locate it again when necessary.
79. Class Name Locator for Product Cards
Suppose an e-commerce page contains:
<div class="product-card">
<h2 class="product-title">Laptop</h2>
</div>
<div class="product-card">
<h2 class="product-title">Phone</h2>
</div>
Locate all product cards:
List<WebElement> products =
driver.findElements(By.className("product-card"));
80. Reading Product Card Text
List<WebElement> products =
driver.findElements(By.className("product-card"));
for (WebElement product : products) {
System.out.println(product.getText());
}
81. Class Name Locator for Product Buttons
<button class="add-to-cart">Add to Cart</button>
driver.findElement(By.className("add-to-cart"))
.click();
82. Class Name Locator for Multiple Product Buttons
List<WebElement> buttons =
driver.findElements(By.className("add-to-cart"));
for (WebElement button : buttons) {
System.out.println(button.getText());
}
83. Class Name Locator for Navigation Links
Links can also have class attributes.
<a href="/products" class="nav-link">Products</a>
<a href="/orders" class="nav-link">Orders</a>
List<WebElement> links =
driver.findElements(By.className("nav-link"));
84. Class Name Locator for Table Actions
<button class="edit-button">Edit</button>
<button class="delete-button">Delete</button>
driver.findElement(By.className("edit-button"))
.click();
85. Class Name Locator in Real-World E-Commerce
Class Name Locators can be useful for product cards, search fields, category controls, add-to-cart buttons, checkout forms, and validation messages when the application provides stable class names.
driver.findElement(By.className("search-box"))
.sendKeys("Laptop");
driver.findElement(By.className("search-button"))
.click();
driver.findElement(By.className("add-to-cart"))
.click();
driver.findElement(By.className("checkout-button"))
.click();
86. Class Name Locator in Real-World Registration
driver.findElement(By.className("first-name"))
.sendKeys("John");
driver.findElement(By.className("last-name"))
.sendKeys("Smith");
driver.findElement(By.className("email-field"))
.sendKeys("[email protected]");
driver.findElement(By.className("password-field"))
.sendKeys("Pass@123");
WebElement terms =
driver.findElement(By.className("terms-checkbox"));
if (!terms.isSelected()) {
terms.click();
}
driver.findElement(By.className("register-button"))
.click();
87. Class Name Locator in Payment Form
List<WebElement> paymentOptions =
driver.findElements(By.className("payment-option"));
for (WebElement option : paymentOptions) {
if ("card".equals(option.getAttribute("value"))) {
option.click();
break;
}
}
88. Class Name Locator in Delivery Options
List<WebElement> deliveryOptions =
driver.findElements(By.className("delivery-option"));
for (WebElement option : deliveryOptions) {
if ("express".equals(option.getAttribute("value"))) {
option.click();
break;
}
}
89. Class Name Locator in Subscription Options
List<WebElement> plans =
driver.findElements(By.className("subscription-option"));
for (WebElement plan : plans) {
if ("premium".equals(plan.getAttribute("value"))) {
plan.click();
break;
}
}
90. Class Name Locator Decision Flow
Start
|
v
Inspect Web Element
|
v
Does it have a class attribute?
|
+---- No ----> Consider ID / Name / CSS / XPath
|
Yes
|
v
Is the class stable?
|
+---- No ----> Find another stable locator
|
Yes
|
v
Is one class token sufficiently specific?
|
+---- Yes ----> Use By.className()
|
+---- No -----> Use CSS Selector or XPath
|
v
Locate Target
|
v
Perform Action
|
v
Validate Result
91. Class Name Locator Validation Checklist
- Inspect the HTML element.
- Find the
class attribute.
- Identify individual class tokens.
- Check whether the class is stable.
- Check whether multiple elements use the same class.
- Use
By.className() with one class token.
- Do not pass multiple space-separated classes to
By.className().
- Use
findElements() for repeated elements.
- Use CSS Selector when multiple class conditions are required.
- Use XPath when complex relationships or conditions are required.
- Use explicit waits for dynamic content.
- Handle iframes before locating inner elements.
- Validate the expected result after performing an action.
92. Common Mistakes with Class Name Locator
Mistake 1: Passing Multiple Classes
By.className("btn btn-primary")
This is incorrect because By.className() expects one class name token.
Mistake 2: Assuming Class Is Unique
Classes are frequently shared by multiple elements.
Mistake 3: Using Dynamic Classes
Generated or hashed class names may change between builds.
Mistake 4: Ignoring Iframes
Elements inside an iframe require switching to the frame first.
Mistake 5: Not Synchronizing Dynamic Elements
Modern applications may render class-based elements after asynchronous operations.
93. Class Name Locator Best Practices
- Prefer stable class names.
- Use one class token with
By.className().
- Do not rely on unstable generated classes.
- Use
findElements() when a class is intentionally shared.
- Use CSS Selector for combinations of multiple classes.
- Use XPath for complex element relationships.
- Use explicit waits for dynamic elements.
- Store important locators in Page Object classes.
- Keep locators readable and meaningful.
- Validate the result after interactions.
94. Class Name Locator and Maintainability
A stable class name can make automation scripts easy to read and maintain.
driver.findElement(
By.className("login-button")
).click();
The locator clearly indicates that the target is the login button.
95. Class Name Locator and Readability
Readable locators help automation engineers understand the purpose of each test step.
driver.findElement(
By.className("email-field")
).sendKeys("[email protected]");
96. Class Name Locator and Test Stability
Test stability depends on the consistency of the application's HTML. A class that remains unchanged across releases can be useful, while a generated class that frequently changes can cause locator failures.
Always inspect the application DOM and understand how its class names are generated before selecting a class-based locator.
97. Class Name Locator Quick Reference
| Action | Example |
| Locate | driver.findElement(By.className("username")) |
| Type | driver.findElement(By.className("username")).sendKeys("admin") |
| Clear | driver.findElement(By.className("username")).clear() |
| Click | driver.findElement(By.className("login-button")).click() |
| Get Text | driver.findElement(By.className("message")).getText() |
| Get Attribute | driver.findElement(By.className("email")).getAttribute("value") |
| Displayed | driver.findElement(By.className("message")).isDisplayed() |
| Enabled | driver.findElement(By.className("submit")).isEnabled() |
| Selected | driver.findElement(By.className("terms")).isSelected() |
| Multiple Elements | driver.findElements(By.className("product-card")) |
98. Class Name Locator Best-Practice Summary
| Practice | Recommendation |
| Stable Class | Prefer class names that remain consistent. |
| Single Token | Pass one class token to By.className(). |
| Multiple Classes | Use CSS Selector when multiple class conditions are required. |
| Shared Class | Use findElements() when multiple elements intentionally share a class. |
| Dynamic Class | Consider another stable locator strategy. |
| Synchronization | Use explicit waits for dynamically rendered elements. |
| POM | Keep important locators inside Page Object classes. |
| Validation | Verify the expected result after interactions. |
99. Interview Question: What is a Class Name Locator?
Answer: A Class Name Locator is a Selenium WebDriver locator strategy that identifies a web element using the value of its HTML class attribute. In Selenium Java, it is implemented using By.className().
100. Interview Question: What is the Syntax of Class Name Locator?
Answer:
driver.findElement(By.className("username"));
For entering data:
driver.findElement(By.className("username"))
.sendKeys("admin");
101. Interview Question: Can Multiple Elements Have the Same Class?
Answer: Yes. Multiple elements commonly share the same class because classes are frequently used for styling and grouping related elements.
102. Interview Question: Can By.className() Accept Multiple Classes?
Answer: No. By.className() expects a single class name token. If an element has multiple classes, use one individual class token or use a CSS Selector for a combination of classes.
103. Interview Question: How Do You Locate an Element with Multiple Classes?
Answer: Use a CSS Selector when you need to target multiple class tokens.
By.cssSelector(".form-control.username")
104. Interview Question: Class Name vs ID Locator?
Answer: ID Locator uses the id attribute, while Class Name Locator uses the class attribute. IDs are intended to uniquely identify elements, whereas classes are commonly shared.
105. Interview Question: Class Name vs XPath?
Answer: Class Name is a simple locator for one class token. XPath provides more advanced capabilities such as text matching, relationships, multiple conditions, and navigation through the DOM.
106. Interview Question: Class Name vs CSS Selector?
Answer: Class Name is convenient when one class token is sufficient. CSS Selectors provide more flexibility for combining classes, attributes, element types, and other CSS matching patterns.
107. Interview Question: What Happens If a Class Does Not Exist?
Answer: If findElement() cannot find a matching element, Selenium can throw NoSuchElementException.
108. Interview Question: How Do You Handle Dynamic Classes?
Answer: Inspect the HTML for a stable ID, name, attribute, CSS pattern, XPath relationship, or dedicated test attribute. Avoid relying on classes that are generated or frequently changed.
109. Interview Question: Can Class Name Be Used for Checkboxes?
Answer: Yes. If checkboxes share a common class, use findElements(By.className()) and identify the required checkbox using another attribute such as value.
110. Interview Question: Can Class Name Be Used for Radio Buttons?
Answer: Yes. Multiple radio buttons can share a class. Use findElements() when necessary and inspect attributes such as value to identify the desired option.
111. Interview Question: Can Class Name Locator Be Used with Explicit Wait?
Answer: Yes. A Class Name locator can be passed to explicit wait conditions.
WebElement element = new WebDriverWait(
driver,
Duration.ofSeconds(10)
).until(
ExpectedConditions.visibilityOfElementLocated(
By.className("username")
)
);
112. Practical Project: Login Automation Using Class Name
driver.get("https://example.com/login");
driver.findElement(By.className("username"))
.sendKeys("admin");
driver.findElement(By.className("password"))
.sendKeys("admin123");
driver.findElement(By.className("login-button"))
.click();
WebElement message =
driver.findElement(By.className("success-message"));
System.out.println(message.getText());
113. Practical Project: Registration Automation
driver.findElement(By.className("first-name"))
.sendKeys("John");
driver.findElement(By.className("last-name"))
.sendKeys("Smith");
driver.findElement(By.className("email-field"))
.sendKeys("[email protected]");
driver.findElement(By.className("password-field"))
.sendKeys("Pass@123");
driver.findElement(By.className("confirm-password"))
.sendKeys("Pass@123");
WebElement terms =
driver.findElement(By.className("terms-checkbox"));
if (!terms.isSelected()) {
terms.click();
}
driver.findElement(By.className("register-button"))
.click();
114. Practical Project: Product Selection
List<WebElement> products =
driver.findElements(By.className("product-card"));
for (WebElement product : products) {
String productName =
product.findElement(
By.className("product-title")
).getText();
if ("Laptop".equals(productName)) {
product.findElement(
By.className("add-to-cart")
).click();
break;
}
}
115. Practical Project: Multiple Checkbox Selection
List<WebElement> skills =
driver.findElements(By.className("skill"));
for (WebElement skill : skills) {
String value =
skill.getAttribute("value");
if ("java".equals(value) ||
"selenium".equals(value)) {
if (!skill.isSelected()) {
skill.click();
}
}
}
116. Complete Class Name Locator Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CompleteClassNameExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com/login");
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.className("username")
)
);
WebElement password =
driver.findElement(
By.className("password")
);
WebElement loginButton =
driver.findElement(
By.className("login-button")
);
username.sendKeys("admin");
password.sendKeys("admin123");
loginButton.click();
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.className("success-message")
)
);
System.out.println(message.getText());
} finally {
driver.quit();
}
}
}
117. Class Name Locator Automation Workflow
Start
|
v
Open Web Page
|
v
Inspect HTML
|
v
Find class attribute
|
v
Identify individual class token
|
v
Is the class stable?
|
+---- No ----> Find another stable locator
|
Yes
|
v
Is one class token sufficient?
|
+---- Yes ----> By.className()
|
+---- No -----> CSS Selector / XPath
|
v
Locate WebElement
|
v
Perform Action
|
v
Validate Result
|
v
End
118. Class Name Locator Final Checklist
- Understand the HTML structure.
- Identify the target element.
- Find the class attribute.
- Separate multiple class tokens mentally.
- Check whether the class is stable.
- Check whether the class is shared.
- Use
By.className() for a single class token.
- Do not pass space-separated class names to
By.className().
- Use
findElements() for multiple matching elements.
- Use CSS Selector for multiple class conditions.
- Use XPath for complex relationships.
- Use explicit waits for dynamic content.
- Handle iframes when required.
- Use Page Object Model in larger frameworks.
- Validate the result after performing actions.
119. Class Name Locator Summary
| Topic | Key Point |
| Locator | Class Name Locator identifies elements using the HTML class attribute. |
| Java Method | By.className() |
| Single Class | Use one class token with By.className(). |
| Multiple Classes | Use CSS Selector when multiple class tokens are required. |
| Repeated Elements | Use findElements(). |
| Dynamic Classes | Prefer stable attributes or relationships. |
| Synchronization | Use explicit waits for dynamic elements. |
| POM | Store locators in page classes. |
| Validation | Verify the expected result after interaction. |
120. Conclusion
The Class Name Locator is an important Selenium WebDriver locator strategy for identifying web elements through their HTML class attribute. In Selenium Java, the basic syntax is By.className("classValue").
Class Name Locators are useful for input fields, buttons, checkboxes, radio buttons, product cards, navigation elements, messages, and many other web components. However, class names are commonly shared between multiple elements, so testers should not automatically assume that a class identifies only one element.
One of the most important rules is that By.className() accepts a single class name token. If an element contains multiple classes such as class="form-control username", do not pass the entire string with spaces to By.className(). Use one class token or switch to a CSS Selector when multiple classes need to be combined.
For reliable automation, prefer stable class names, avoid generated or frequently changing classes, use findElements() when classes are shared, apply explicit waits for dynamic elements, and use Page Object Model to organize locators in larger Selenium projects.
To learn more about Selenium WebDriver, locators, WebElements, TestNG, Page Object Model, automation frameworks, and real-time testing projects, visit the JustAcademy's Selenium Training Course.
To explore or register for a course demo, visit Register for Course Demo.