Selenium WebDriver provides multiple ways to locate elements, and one of them is using their class
attribute with the method By.className()
.
π What is the class
Attribute in HTML?
The class
attribute in HTML is commonly used to apply CSS styles or JavaScript functions to groups of elements. It’s often shared by multiple elements.
<button class="btn submit-btn">Submit</button>
✅ When to Use By.className()
?
- ✅ When elements have a common styling class name
- ✅ When you want to select groups of elements
- ✅ When the class name is unique or reliably identifies the element
π Syntax in Java
driver.findElement(By.className("class_name"));
π‘ HTML Example
Example of a form button using the class name:
<button class="login-btn">Login</button>
π» Selenium + Java Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClickByClassName {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Locate element using className
WebElement loginButton = driver.findElement(By.className("login-btn"));
loginButton.click();
driver.quit();
}
}
✅ Best Practices
Tip | Why? |
---|---|
Use single class name only | By.className() doesn’t support multiple class names (like “btn primary”) |
Validate uniqueness | Make sure class uniquely identifies the element |
Use findElements() for multiple elements |
If multiple elements share the same class |
⚠️ Common Issues
Issue | Solution |
---|---|
Multiple class names | Use only one class name. Prefer By.cssSelector() for more complex selection. |
NoSuchElementException | Class might not exist or element not loaded yet → use waits |
π§ͺ Example with Multiple Matching Elements
If you want to click the second item in a list of elements with the same class:
List<WebElement> items = driver.findElements(By.className("menu-item"));
items.get(1).click(); // Click second item
π Summary
By.className()
is useful for locating elements with simple, single class names.- It does not work with compound class names like "btn primary".
- For more complex needs, prefer
By.cssSelector()
orBy.xpath()
.
π What's Next?
Explore other Selenium locators: