Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element contains specific class attribute

How can I check if a selenium web element contains a specific css class.

I have this html li element

<li class="list-group-item ng-scope active" ng-repeat="report in lineageController.reports" ng-click="lineageController.activate(report)" ng-class="{active : lineageController.active == report}"> 

As you can see inside class attribute there is an active class.

My problem is that I have this element and I want to do a check based on if the class attribute has that "active" value among the others, being more elegant solution then using xpath.

How can I do this?

like image 867
aurelius Avatar asked Sep 22 '15 09:09

aurelius


People also ask

How do you check if an element has a specific class in Javascript?

The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do you locate an element by partially comparing its attributes in xpath?

We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.

How do you select an element with the class name?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)


1 Answers

Given you already found your element and you want to check for a certain class inside the class-attribute:

public boolean hasClass(WebElement element) {     String classes = element.getAttribute("class");     for (String c : classes.split(" ")) {         if (c.equals(theClassYouAreSearching)) {             return true;         }     }          return false; } 

#EDIT As @aurelius rightly pointed out, there is an even simpler way (that doesn't work very well):

public boolean elementHasClass(WebElement element, String active) {     return element.getAttribute("class").contains(active); } 

This approach looks simpler but has one big caveat:

As pointed out by @JuanMendes you will run into problems if the class-name you're searching for is a substring of other class-names:

for example class="test-a test-b", searching for class.contains("test") will return true but it should be false

#EDIT 2 Try combining the two code snippets:

public boolean elementHasClass(WebElement element, String active) {     return Arrays.asList(element.getAttribute("class").split(" ")).contains(active); } 

That should fix your caveat.

like image 59
drkthng Avatar answered Sep 19 '22 08:09

drkthng