aurelius aurelius - 1 month ago 4
Java Question

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?

Answer

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:

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