We use findElement by className to quickly find a web page element using its CSS class name. This helps us interact with buttons, text boxes, or other parts of a webpage during testing.
findElement by className in Selenium Java
WebElement element = driver.findElement(By.className("class-name"));Replace "class-name" with the actual class attribute value of the element.
This finds the first element matching the class name on the page.
submit-btn, often a submit button.WebElement button = driver.findElement(By.className("submit-btn"));WebElement message = driver.findElement(By.className("alert-message"));WebElement inputField = driver.findElement(By.className("input-text"));This program opens a browser, goes to a test page, finds a button by its class name submit-btn, and prints if it is visible or not. It handles the case if the element is missing.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FindElementByClassNameExample { public static void main(String[] args) { // Set path to chromedriver executable if needed // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/testpage"); // Find element by class name WebElement button = driver.findElement(By.className("submit-btn")); // Check if button is displayed if (button.isDisplayed()) { System.out.println("Button found and visible."); } else { System.out.println("Button found but not visible."); } } catch (Exception e) { System.out.println("Element not found: " + e.getMessage()); } finally { driver.quit(); } } }
Class names should not contain spaces; if the element has multiple classes, use only one class name at a time.
If multiple elements share the same class, findElement returns the first one found.
Use findElements to get all elements with the same class name.
findElement by className helps locate a single web element using its CSS class.
It returns the first matching element or throws an error if none found.
Useful for interacting with buttons, inputs, or messages identified by class.