0 votes
1 view
in DevOps and Agile by (19.8k points)

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 a more elegant solution then using XPath.

How can I do this?

1 Answer

0 votes
by (63.4k points)

I am assuming that you have already found your element and you want to check for a certain class within the class-attribute. Here’s a code to do that:

public boolean hasClass(WebElement element) {

    String classes = element.getAttribute("class");

    for (String c : classes.split(" ")) {

        if (c.equals(theClassYouAreSearching)) {

            return true;




    return false;



There is a simpler way (but usually it doesn't work very well when compared to the first method shown above):

public boolean elementHasClass(WebElement element, String active) {

    return element.getAttribute("class").contains(active);


This approach looks simpler but has one limitation. You may get an error(s) if the class-name you're searching for is a substring of other class-names:

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !