+ Reply to Thread
Results 1 to 2 of 2

Thread: find all parent elements

  1. #1

    find all parent elements

    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 accomplish this?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    41
    You can just use XPath to get the parent element until you get to the page root. So something like this:
    Code:
    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);
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts