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("../..")

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.