How to count HTML child tag in Selenium WebDriver using Java

Viewed 26617

In Selenium JAVA WebDriver - How can I count child tags? Example:

<div class="subcategory_container">
  <div class="products_container">
     <div class="product_row">
       <form class="product_container">
       <form class="product_container">
       <form class="product_container">
     </div>
   </div>
</div>

I want to count how many form tag are there under product_row div? Thanks

5 Answers

Every element has an attribute called childElementCount. You can use WebElement.getAttribute() function to get an immediate value.

WebElement element = driver.findElement(By.className("product_row"));
int numberOfChilds = Integer.parseInt(element.getAttribute("childElementCount"));

Because getAttribute() returns a String, we have to cast it to an int.

Related