Selenium Assert Element has Class

Profile picture for user arilio666

In selenium, we can check if an element has a class attribute using the getAttribute() method, which is used to get the value of the class attribute.

This article will help us understand how to verify the value and attribute using id, class, name, or even xpath.

        public static void main(String[] args) throws InterruptedException {
        ChromeDriver driver = new ChromeDriver();
        WebElement classEle = driver.findElement(By.xpath("(//input[@class='form-text required'])[1]"));
        String classEleText = classEle.getAttribute("class");
        if (classEleText.equals("form-text required")) {
            System.out.println("class attribute contains: " + classEleText);
        } else {
            System.out.println("class attribute does not contain: " + classEleText);
  • First, using XPath, we took the class of the username field and stored it in a variable.
  • Then use getAttribute() and pass in the class attribute.
  • Then, in the end, we check with the if-else statement that the class has the value "form-text required."