Selenium get the parent of an element

1 min


637
637 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!

637
637 points

What's Your Reaction?

cute cute
0
cute
scary scary
0
scary
wtf wtf
1
wtf
geek geek
0
geek
WIN WIN
0
WIN
Love Love
0
Love
OMG OMG
0
OMG
Angry Angry
0
Angry
Lol Lol
0
Lol
Test engineer

0 Comments

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

Choose A Format
Trivia quiz
Story