6

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

cm007
  • 1,352
  • 4
  • 20
  • 40

2 Answers2

9

If I understand your question correctly you want to find the By element and then the parents up until the root.

You can just use XPath to get the parent element until you get to the page root. 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 on the body element instead of the html one.

Also note that this is fairly slow, especially if its a deeply nested element. A faster alternative would be to use ExecuteScript to run a javascript snippet that uses the same logic and then returns all the elements at once.

prestomanifesto
  • 12,528
  • 5
  • 34
  • 50
  • As mentionned here https://stackoverflow.com/a/45769799/233906 `By.XPath("./ancestor-or-self::*")` should achieve the same and return all ancestors (including parent). – Cerber Apr 09 '21 at 14:35
1

I created WebElement extension, I hope 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;
    }
}