Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if dom has a class using WebDriver (Selenium 2)?

Tags:

I am very new to Selenium, so my apologies if it's a silly question. I have successfully wired up IntelliJ (Play! framework) with Selenium, and created some tests using firefoxDrivers.

I'm trying to check if the page had been validated properly.

long story short, I'm selecting an element like this:

WebElement smallDecel = firefoxDriver.findElement(By.cssSelector("#configTable tr:nth-child(2) td .playerDecelInput")); 

I do some further operations (clear and change the value, submit the 'form'), and then I want to check if the TD the input sits in was given another class.

So, the question is - is there a simple technique I can use to find out if a WebElement / DOM has a class specified?

like image 912
Klon Avatar asked Nov 23 '11 12:11

Klon


People also ask

How do I find class in Selenium?

We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.

How do I check if an element is available in Selenium?

New Selenium IDE We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.

What is DOM in Selenium Webdriver?

DOM stands for Document Object Model. In simple words, DOM specifies the structural representation of HTML elements. There are four ways through which we can identify and locate a web element using DOM. getElementById. getElementsByName.

Is DOM a locator in Selenium?

The different locators in Selenium are as follows:By DOM structure or xpath: find_element_by_xpath. By link text: find_element_by_link_text. By partial link text: find_element_by_partial_link_text. By HTML tag name: find_element_by_tag_name.


2 Answers

To expand on Sam Woods' answer, I use a simple extension method (this is for C#) to test whether or not an element has a specified class:

public static bool HasClass( this IWebElement el, string className ) {     return el.GetAttribute( "class" ).Split( ' ' ).Contains( className ); } 
like image 99
Sam Peacey Avatar answered Oct 06 '22 08:10

Sam Peacey


Once you find the element, you can just call myElement.GetAttribute("class"). Then you can parse the string that is returned and see if it contains or does not contain the class name you care about.

like image 35
Sam Woods Avatar answered Oct 06 '22 09:10

Sam Woods