If I understand your question correctly, you want to find the By element, and then the parents to the root.
You can simply use XPath to get the parent until you get to the root of the page. So something like this:
public ReadOnlyCollection<IWebElement> FindElementTree(By by) { List<IWebElement> tree = new List<IWebElement>(); try { IWebElement element = this.driver.FindElement(by); tree.Add(element); //starting element do { element = element.FindElement(By.XPath("./parent::*")); //parent relative to current element tree.Add(element); } while (element.TagName != "html"); } catch (NoSuchElementException) { } return new ReadOnlyCollection<IWebElement>(tree); }
Optionally, you can stop the body element instead of html .
Also note that this is rather slow, especially if its a deeply nested element. A faster alternative would be to use ExecuteScript to run a javascript fragment that uses the same logic and then returns all the elements at once.
source share