15

I've tried

private WebElement getParent(final WebElement webElement) {
    return webElement.findElement(By.xpath(".."));
}

But I'm getting:

org.openqa.selenium.InvalidSelectorException: The given selector .. is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: The result of the xpath expression ".." is: [object XrayWrapper [object HTMLDocument]]. It should be an element. Command duration or timeout: 10 milliseconds For documentation on this error,

Is there a way to get the parent of current element? Thanks

petabyte
  • 1,487
  • 4
  • 15
  • 31

2 Answers2

28

There are a couple of ways you can accomplish this. If you insist on using XPath to do it, you need to add the context node to the locator, like this:

WebElement parentElement = childElement.findElement(By.xpath("./.."));

Alternatively, you can use the JavascriptExecutor interface, which might be slightly more performant. That would look like this:

// NOTE: broken into separate statements for clarity. Could be done as one statement.
JavascriptExecutor executor = (JavascriptExecutor)driver;
WebElement parentElement = (WebElement)executor.executeScript("return arguments[0].parentNode;", childElement);
JimEvans
  • 27,201
  • 7
  • 83
  • 108
3

Alternatively, can you try using Javascript Executor?

WebElement childElement = driver.findElement(By.id("someIdHere"));

WebElement parent = (WebElement) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].parentNode;", childElement);
Ravindra Gullapalli
  • 9,049
  • 3
  • 48
  • 70