How to find all parent elements using Selenium C # WebDriver?

I have a variable that is a By class. I want to call FindElements to return the corresponding element, as well as all the parent elements of this By . How to do it?

+4
source share
2 answers

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.

+6
source

I created a WebElement extension, hopefully useful.

 public static IWebElement GetElementParentByClass(this IWebElement element, string ClassName) { try { IWebElement parent = element; do { parent = parent.FindElement(By.XPath("./parent::*")); //parent relative to current element } while (!parent.GetAttribute("class").Equals(ClassName)); return parent; } catch (Exception ex) { return null; } } 
0
source

Source: https://habr.com/ru/post/1393203/


All Articles