Selenium how to get all elements inside a WebElement

Tags: , , ,



I’m trying to get all the elements inside a selenium WebElement, for example:

<div>
    <element>
        <header>header</header>
        <p>Paragraph</p>
    </element>
    <element>
        <p>Another Paragraph</p>
    </element>

</div>

I want to get a list of all the elements inside including child elements, like so…

  1. div
  2. element
  3. header
  4. paragraph
  5. element
  6. paragraph

So I’ve tried this

element.findElements(By.xpath("*"))

but this would return only

  1. element
  2. element

So then I tried a recursive method to get all of the childs

private static ArrayList<WebElement> getAllElements(WebElement element, ArrayList<WebElement> ret) {
    ret.add(element);
    List<WebElement> childs = element.findElements(By.xpath("*"));
    for(WebElement e: childs)
        getAllElements(e,ret);
    return ret;
}
private static List<WebElement> getAllElements(WebElement element) {
   return getAllElements(element,new ArrayList<WebElement>());
}

But querying findElements() takes too long

I’m thinking there must be a xpath way, but I can’t seem to find it

Answer

We can use WebElement.findElements method to get list of all the elements inside element.

For above HTML, to get list of all elements present inside div, we can use below code:

// Get webelement for div tag
WebElement element = driver.findElement(By.tagName("div"));

// Below will return a list of all elements inside element
List<WebElement> webEleList = element.findElements(By.xpath(".//*"));

//For above given HTML it will print 5. As there are 5 elements inside div
System.out.println(webEleList.size());


Source: stackoverflow