Search code examples
appium

Get Parent element from child element in appium


I have a recycler view. All Rows have same ids. Each Row has checkbox and text and these elements also have same ids. But some rows does not have checkboxes.

So what i am trying to do is locate checkbox by id, then get its parent node and locate its child.

MobileElement childElement= driver.findElement(By.id("checkbox-child"));
MobileElement parentElement= // need to know how to do it 

parentElement.findElement(By.id("text-child")).getText();

So i wanted to know how can i get parent element from its child Element.

enter image description here


Solution

  • An overlay of one way I could think of solving this is :

    List<WebElement> listParent = driver.findElements(By.id("parentID")); //Requires parent's resource-id.
    for(int i=0;i<listParent.size();i++){
        String parentXPath = "//android.widget.RelativeLayout["+i+"]"
        String childXPath = parentXPath + "//android.widget.Checkbox"; //should get you the child corresponding to the specific Relative Layout
        MobileElement parentElement= driver.findElement(By.XPath(parentXPath); 
        if(isElementPresent(By.XPath(childXPath))){
           parentElement.findElement(By.id("text-child")).getText();
        }
    

    Would try this on my end as well.