How to check if element contains specific class attribute How to check if element contains specific class attribute selenium selenium

How to check if element contains specific class attribute


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;}

#EDITAs @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 2Try 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.


The answer provided by @drkthng works but you might have a case where the class name is a subset of another class name. For example:

<li class="list-group-item ng-scope active">text</li>

If you wanted to find the class "item" then the provided answer would give a false positive. You might want to try something like this:

public boolean hasClass(WebElement element, String htmlClass) {    String classes = element.getAttribute("class").split("\\s+");    if (classes != null) {        for (String classAttr: classes) {            if (classAttr.equals(htmlClass)) {                return true;            }        }    }    return false;}


Use javascript: classList.contains

 WebElement element = By.id("id"); String className = "hidden"; JavascriptExecutor js = (JavascriptExecutor) driver; Boolean containsClass = js.executeScript("return arguments[0].classList.contains(arguments[1])", element, className);