ram
ram

Reputation: 497

Find an element within element using @FindBy Annotation.

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)

Upvotes: 7

Views: 3858

Answers (4)

James
James

Reputation: 45

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;

Upvotes: 0

karunakar Reddy
karunakar Reddy

Reputation: 21

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.

Upvotes: 1

Anand Thanappan
Anand Thanappan

Reputation: 93

@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));
}

Upvotes: 0

Saifur
Saifur

Reputation: 16201

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;

Upvotes: 2

Related Questions