Find Element by Class Name

To find the web element identified by the given class name, programmatically using Selenium in Java, use WebDriver.findElement(By.className()) function and pass the name as string to className() method.

WebDriver.findElement(By.className("x")) returns the first web element with the specified class name "x".

The following is a simple code snippet where we find the first web element in the web page with the class name x.

WebElement e = driver.findElement(By.className("x"));
ADVERTISEMENT

Example

In the following program, we write Java code to find the first web element with the class name "mp-h2", and print the text in that element.

Java Program

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://en.wikipedia.org/wiki/Main_Page");

        WebElement e = driver.findElement(By.className("mp-h2"));
        System.out.println(e.getText());
        
        driver.quit();
    }
}

Output

From today's featured article