29

I have a Test which search for <span class="legend">. On a previous level I have a fieldset which contains several values. Here is my problem. I don't get the locator for this fieldset.

First of all I get a list with all class=legend objects:

List<WebElement> groupList = driver.findElements(By.className("legend"));

This works perfectly, I have a list with several Webelements.

Now I want to iterate this list and save every value from the fieldset of the previous level only. The problem is that Selenium does not find the id of the fieldset.

I tried tempGroupElement.getAttribute("id") to get the id but it does not work.

Any idea?

John Smith
  • 7,243
  • 6
  • 49
  • 61
Ed H
  • 513
  • 2
  • 5
  • 7

3 Answers3

49

I have a method for this in C#.

public static IWebElement GetParent(IWebElement e)
{
   return e.FindElement(By.XPath(".."));
}

Hope it helps :)

Tedesco
  • 880
  • 6
  • 10
14

You can use WebElement.findElement(By.xpath("parent::*"))

I tried, it works in selenium.

amurra
  • 15,221
  • 4
  • 70
  • 87
abuuu
  • 367
  • 3
  • 14
  • 1
    This is my preferred way of doing it. With the right Xpath locator, you can travel up and down the DOM until you get to what you are looking for. It's very useful in situations where you want to find a child element with a parent that contains some text (for example). – djangofan Feb 19 '15 at 15:41
  • Isnt XPath not supported by Safari? – Martin Kersten May 13 '16 at 10:33
6

This will create an extension on top of IWebElement that will let you call GetParent directly on the child IWebElement

public static class MyExtensions
{
    public static IWebElement GetParent(this IWebElement node)
    {
        return node.FindElement(By.XPath(".."));
    }
}  

Example usage...

IWebElement node = WebDriver.FindElement('..');
IWebElement parent = node.GetParent();
TWilly
  • 4,863
  • 3
  • 43
  • 73
  • Is there something that simple for siblings? – Ywapom Jun 18 '18 at 17:39
  • `FindElement` will throw `NoSuchElementException` if it doesn't find any. IMO it's safer to use `FindElements(By.XPath("..")).SingleOrDefault()` That way it will return null if nothing is found. Really wish Selenium support some method like `FindElementIfAny` because sometimes I really don't want an exception thrown. – Nam Le Jul 09 '21 at 02:38