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>
-
//span/parent::*
- returns any element which is direct parent.
In this case output is <div class="parent">
-
//span/parent::div[@class="parent"]
- returns parent element only of exact node type and only if specified predicate is True.
Output: <div class="parent">
-
//span/ancestor::*
- returns all ancestors (including parent).
Output: <div class="parent">
, <nav class="second_level_ancestor">
, <div class="third_level_ancestor">
...
-
//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">
...
-
//span/ancestor::div[2]
- returns second ancestor (starting from parent) of typediv
.
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
Take a look at the possible XPath axes, you are probably looking for parent
. Depending on how you are finding the first element, you could just adjust the xpath for that.
Alternatively you can try the double-dot syntax, ..
which selects the parent of the current node.