To find parent by knowing his child, use xpath:
//element/…
If you want to get webelement dynamically, I would recommend to define parent by annotation (as others). However, it could be done like that:
WebElement parentElement = driver.findElementByXPath(childElement.getAttribute(“xpath”) + “/…”);
Awesome ~
To find parent by xpath “//element/…” works well on appium, but get the element’s attribute “xpath” will throw an error. PS: I test on mobile native element, i guess that the native element do not have the ‘xpath’ attribute
Using inspect.exe (which is installed with the Windows SDK) I found that there was a relationship between the Id’s of a Parent and its Child elements in a Windows Forms ListView. I suspect this relationship may also apply (is likely to apply) to other OS’s and controls.
In my case I have a WinForm ListView control with a number of Items in it, and each item has 4 SubItems - each being a child element of the Item element.
Each Item is, in its turn, is a child element of the ListView control.
If the ListView has an Id, say, of 12345.6
Each ListViewI Item has an Id of 12345.6.i where i is the index of the Item in the ListView
Each ListView SubItem has an Id of 12345.6.i.s where s in the index of the SubItem in Item i
Thus to access the or Parent or Grandparent by Id from the Child element simply truncate the Child element Id by the appropriate number of sub-indices. Its quick, no messing with XPath.