0

Is there a way to get the CSS class that has been applied to the selected WebElement, we do have the getCssValue method, however it provides the value of the specific attribute and not the class that has been applied to the WebElement

Prabhu R
  • 13,836
  • 21
  • 78
  • 112

3 Answers3

1

Use getAttribute(attributeLocator) function,

Specify the Xpath of the element for the class you needed to retrieve.

  selenium.getAttribute(//xpath@class);
newTag
  • 2,149
  • 1
  • 22
  • 31
1

First get the WebElement using any locator like Xpath,id etc., Now apply get attribute method on the WebElement as below:

WebDriver driver=new WebDriver();
WebElement element=driver.findelement(Bylocator);
String className=element.getattribute("class");

This method can be used to get any attributes of a particular WebElement like href attribute of a link etc.

Example:

WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
WebElement element=driver.findElement(By.id("Email"));
System.out.println("Placeholder of email text box: "+ element.getAttribute("placeholder"));

The above code will print the placeholder displayed in the Email box.

Output displayed in the console:

Placeholder of email text box: Enter your email
SaiPawan
  • 1,189
  • 7
  • 20
-3

I think the Chrome Debug Tool is helpful (Press F12 to access it)

Right click on an element and Inspect it. In the Styles tag , the classes are shown with match css rules!

Yongfeng
  • 666
  • 7
  • 22