7

For Example,

WebElement parentEle = driver.findElement(By.id("xyz"));
WebElement childEle = parentEle.findElement(By.id("abc"));
childEle.click();

In the above example, We are finding childEle with in parentEle. How can we achieve this using @FindBy annotation (in conjunction with PageFactory)

ram
  • 447
  • 2
  • 5
  • 12

4 Answers4

2

First of all why do you need to find child from a parent if the child has a UNIQUE id? The main purpose of id is to provide the flexibility of finding the element with a unique selector.

In case if the child element is really nested to other, find that with xpath. I often use that.

@FindBy(how = How.XPATH, using = "//something/something")
private WebElement TestElement;

Or with ID

@FindBy(how = How.ID, using = "abc")
private WebElement TestElement;
Saifur
  • 16,081
  • 6
  • 49
  • 73
  • 3
    Thanks for the reply Saifur. I understand. When we are going by id we can directly find it. But I just quoted it as an example. Lemme explain my scenario. I have multiple li tags with same classnames but different values. And each li have their children. So I need to get the parent tag(li here) and work on its child elements. I can achieve this by normal findElement way, but I would like to know how we can do it by using @FIndBy annotations. Plz reply. – ram Jul 02 '15 at 01:54
1

This can be achieved in couple of steps:

//identify parent element with @FindBy annotation
    1) @FindBy(className="locator")
       List<WebElement> parent;

//loop through each parent to get child(<li> in your case) of each parent    
    2) for(WebElement list_items:Parent){
       list_items.findElement(By.xpath("child locator"));

I had used this approach and was able to achieve the desired results. Hope this explains your query as well.

0
@FindBy (id = "abc")
private WebElement TestElement;

In your page factory try this and call that method from your test method.

public WebElement Child_Of_ParentElement(WebElement TestElement, String Child_Id)
{
  return TestElement.findElement(By.id(Child Id));
}
0

As stated in other answers I would use xpath although you would have to rewrite the root path for each child element, unless you make a string constant or something but that could start to get messy.

// Child 1
@FindBy(xPath = "//[@id='xyz']/[@id='abc']";
private WebElement childAbcOfParentXyz;
// Child 2
@FindBy(xPath = "//[@id='xyz']/[@id='def']";
private WebElement childDefOfParentXyz;
James
  • 35
  • 1
  • 6