seleniumselenium-webdriverpageobjects

Is there way to a find child element from existing element in Selenium with Java?


Say, there are multiple elements and their and multiple child elements. I have selected the parent elements and from the code the I want to select the child elements.

<html>
<body>
<div>
    This is div 1
    <p>
        This is paragraph 1 under div 1.
    </p>
</div>

<div>
    This is div 2
    <p>
        This is paragraph 2 under div 2.
    </p>
</div>


<div>
    This is div 3
    <p>
        This is paragraph 3 under div 3.
    </p>
</div>

</body>
</html>

Here lets say I have the xpaths for the divs. Something like @FindBy(xpath="(//div)[1]") Webelement div_1;

But I do not define the child element using the Findby tag. I would like to find the child element using the div_1 element in my actual test code itself. How can I do this?


Solution

  • You can do this:

    WebElement div = driver.findElement(By.xpath("//div[@class='something']");
    

    And later you can do:

    div.findElement(By.xpath("//div"));
    

    Or you can use the plural form:

     List<WebElement> subDivs = div.findElements(By.tagName("div"));
    

    Not sure if this is what you are looking for.