1

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?

2 Answers 2

3

If i understood correct you need something like this

@FindBy(xpath="(//div)[1]")
WebElement parent;

WebElement child = parent.findElement(By.xpath("./p"));
Sign up to request clarification or add additional context in comments.

Comments

2

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.

4 Comments

I am looking for this. And this is what I had tried earlier but it did not work. Is there any other alternative?
Yes, there is - doing it properly :) What do you mean by not working? If you provide exact structure of the dom I can help you to fix the issue.
As of now, I don't have any such example. I'll be sure to post when I get some thing like that. Thank you.
No worries when you are ready

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.