Get the Parent Node of the Current Selenium WebElement

There are times that the parent is required from the child element.

There are two options JavaScript or XPath:

WebElement myElement = driver
        .findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver)
        .executeScript(
        "return arguments[0].parentNode;", myElement);
WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath(".."));

But what if the parent of the parent is required?

The JavaScript would be

return arguments[0].parentNode.parentNode;

and the XPath will be

By.xpath("../..")

Share This

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>