How to check if dom has a class using WebDriver (Selenium 2)?

SeleniumAutomation TestingTesting Tools

We can check if DOM has a class using Selenium webdriver. We can use the findElements method to obtain the list of elements having a particular class. Then pass By.className or By.xpath or By.cssSelector as a parameter to the method.

The class name we want to search is passed as a parameter to that method. Let us investigate the below html code for an ul element having class value as toc chapters. Then obtain its sub-elements.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class ClassAttrb{
   public static void main(String[] args) {
      System.setProperty("",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element with class attribute
      WebElement m=
      driver.findElements(By.xpath("//ul[@class='toc chapters']"));
      //identify children
      List<WebElement> ch = m.findElements(By.xpath("./child::*"));
      // iterate through sub elements
      for ( WebElement i : ch ) {
         // get text for children


Updated on 01-Feb-2021 12:26:58