Hideandseek
Hideandseek

Reputation: 391

Selenium WebDriver cannot find element

Here is the sample webpage code

<div class="size1of2 fllt">
    <div id="iad-service" class="tmargin2 rite fllt service-check"></div>
    <div class="fk-font-13 fk-font-regular">hi</div>
</div>

I want to find the "class" element using Selenium WebDriver.

Here is the code I tried.

String abc = driver.findElement(By.xpath("//div[contains(@id,'iad-service')]/@class")).getText();
System.out.println(abc);

When I tried this code(//div[contains(@id,'iad-service')]/@class) in the XPath Checker Addon, I am getting this output.

tmargin2 rite fllt service-check

But using WebDriver, I am getting an error. I want the output to be the content of the class which is.

tmargin2 rite fllt service-check

Where am I doing wrong?

Upvotes: 2

Views: 1807

Answers (2)

Juhi Saxena
Juhi Saxena

Reputation: 1217

You can use this:

WebElement id=wd.findElement(By.id("iad-service"));
    String className=id.getAttribute("class");

Upvotes: 0

guido
guido

Reputation: 19194

You need to fetch the div element, then retrive the class attribute value:

String abc = driver.findElement
               (By.xpath("//div[contains(@id,'iad-service')]")).getAttribute("class");

Upvotes: 1

Related Questions