Select parent element of known element in Selenium Select parent element of known element in Selenium selenium selenium

Select parent element of known element in Selenium


There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.

Java:

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

XPath:

WebElement myElement = driver.findElement(By.id("myDiv"));WebElement parent = myElement.findElement(By.xpath("./.."));

Obtaining the driver from the WebElement

Note: As you can see, for the JavaScript version you'll need the driver. If you don't have direct access to it, you can retrieve it from the WebElement using:

WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();


Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">    <nav class="second_level_ancestor">        <div class="parent">            <span>Child</span>        </div>    </nav></div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">


Let's consider your DOM as

<a>    <!-- some other icons and texts -->    <span>Close</span></a>

Now that you need to select parent tag 'a' based on <span> text, then use

driver.findElement(By.xpath("//a[.//span[text()='Close']]"));

Explanation: Select the node based on its child node's value