findElement by className in Selenium Java - Build an Automation Script
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; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class LoginButtonTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/login"); } @Test public void testLoginButtonClickableByClassName() { // Wait until the login button is clickable WebElement loginButton = wait.until( ExpectedConditions.elementToBeClickable(By.className("btn-login")) ); // Assert the button is displayed Assert.assertTrue(loginButton.isDisplayed(), "Login button should be visible"); // Click the login button loginButton.click(); // Wait until URL changes to dashboard wait.until(ExpectedConditions.urlToBe("https://example.com/dashboard")); // Assert the URL is correct Assert.assertEquals(driver.getCurrentUrl(), "https://example.com/dashboard", "URL should be dashboard after login"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test class uses Selenium WebDriver with Java and TestNG for assertions.
setUp() opens the browser and navigates to the login page.
The test testLoginButtonClickableByClassName waits explicitly for the login button located by By.className("btn-login") to be clickable. This avoids timing issues.
It asserts the button is visible, then clicks it.
After clicking, it waits for the URL to change to the dashboard URL and asserts the URL is exactly as expected.
tearDown() closes the browser to clean up.
This structure follows best practices: explicit waits, proper locator usage, and clean test lifecycle.
Now add data-driven testing with 3 different class names for buttons to verify each is clickable and leads to correct URLs
Practice
findElement(By.className("btn-primary")) do in a test script?Solution
Step 1: Understand the method purpose
The methodfindElementlocates a single element on the page.Step 2: Analyze the locator type
UsingBy.className("btn-primary")targets elements with the CSS class "btn-primary".Final Answer:
It finds the first web element with the CSS class "btn-primary" on the page. -> Option CQuick Check:
findElement + className = first matching element [OK]
- Confusing findElement with findElements (plural)
- Using className to find by ID or tag
- Expecting multiple elements returned
Solution
Step 1: Recall correct method usage
The correct method to locate by class name isBy.className()with capital N.Step 2: Check syntax correctness
driver.findElement(By.className("login-button")); uses the exact correct syntax:By.className("login-button").Final Answer:
driver.findElement(By.className("login-button")); -> Option BQuick Check:
Correct method name is className with capital N [OK]
- Using By.class instead of By.className
- Wrong method casing like class_name or classname
- Missing quotes around class name
<button class="submit-btn primary">Submit</button>
What will the following code return?
WebElement btn = driver.findElement(By.className("primary"));
System.out.println(btn.getText());Solution
Step 1: Locate element by class name "primary"
The button has class "primary" among others, so it matches.Step 2: Get the text of the found element
ThegetText()method returns the visible text inside the button, which is "Submit".Final Answer:
Submit -> Option AQuick Check:
findElement by className finds element, getText returns inner text [OK]
- Expecting class name as text output
- Confusing class attribute with element text
- Assuming exception if multiple classes present
WebElement element = driver.findElement(By.className("btn primary"));It tries to find an element with classes "btn" and "primary".
Solution
Step 1: Understand className locator rules
TheBy.classNamelocator accepts only a single class name without spaces.Step 2: Identify the error in locator usage
Using "btn primary" with space is invalid and causes an error; it cannot find elements with multiple classes this way.Final Answer:
className locator cannot contain spaces; it matches only one class. -> Option DQuick Check:
className accepts single class only, no spaces [OK]
- Trying to find multiple classes with space-separated string
- Expecting findElement to accept compound class selectors
- Confusing className with CSS selector syntax
Solution
Step 1: Understand limitation of className locator
TheBy.classNamelocator cannot handle multiple classes separated by spaces.Step 2: Use CSS selector for multiple classes
The CSS selector.nav-item.activematches elements with both classes and works correctly.Step 3: Compare other options
driver.findElement(By.className("nav-item active")).click(); is invalid due to space in className; driver.findElement(By.className("nav-item")).click(); matches only one class; driver.findElement(By.xpath("//button[@class='nav-item active']")).click(); uses XPath but is less concise.Final Answer:
driver.findElement(By.cssSelector(".nav-item.active")).click(); -> Option AQuick Check:
Use CSS selector for multiple classes, not className [OK]
- Using className with multiple classes separated by space
- Using only one class when both are needed
- Ignoring CSS selectors as a better alternative
Ready to prove it?
Pass the test and this pattern moves unknown
