Selenium get the parent of an element


638
638 points
how to get the parent of an element
how to get the parent of an element

Selenium get the parent of an element

You might run a in a situation when you selected an element and you need to get it’s parent . We can do this using xpath . So if you already did a request to get the element , this is how to get parent of an element.

If you already selected an element and want to get its parent, you can call find(:xpath, '..') on it.
To get the parents parent, call find(:xpath, '../..').

How to:

Find a link which contains a gitlab icon and check that it links to the correct page:

<a href="http://gitlab.com/">
  <li class="icon gitlab"></li>
</a>
link = page.find("a .icon.gitlab").find(:xpath, '..')
link[:href].should == "http://gitlab.com/

Have a look at this tutorial that will give you a good overview for xpath expressions.

Selenium get parent of element in JavaScript:

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

Selenium get parent of element in Java:

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

Like it? Share with your friends!

638
638 points
Test engineer

0 Comments

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

5 − 5 =