How to get css class name using Selenium?

We can get the css class name of an element with Selenium webdriver. To obtain the class name attribute of an element in the html document, we have to use the getAttribute() method. Then the class value is passed as a parameter to the method.

Let us consider the below html code with class attribute.

The class attribute is having the value as gsc-input. This can be obtained with the help of getAttribute() method.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;

public class GetClssAttribute{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      String url = "";
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement("gsc-i-id1"));
      // get class attribute with getAttribute()
      String val = l.getAttribute("class");
      System.out.println("Class attribute value: " + val);


Updated on: 18-Sep-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started