JackhammersForWeeks
JackhammersForWeeks

Reputation: 967

Trouble using parent::* axes in selenium web driver

I am trying to use a wildcard to navigate up the DOM in selenium, using something like this...

    ArrayList<WebElement> list = (ArrayList<WebElement>) driver.findElements(By.xpath("//div[contains(text(),'div_text')]/parent::*]"));

to try to get all the parent elements of the div that has 'div_text'. This only seems to return the immediate parent, not ALL the parents. I need to go a variable number of nodes up the DOM.

Once I get the list, I plan to iterate through with

for(WebElement e: list)
   if(e.getTagName().equals("table") && e.getAttribute("class").equals("blah")
       e.click();

Agreed that this is not the most efficient approach, but more complex xpath expressions like

driver.findElements(By.xpath("//div[text()='title']/[name(parent::*) = 'table'"));

do not seem to work in web driver.

Thanks for any insight on this.

Upvotes: 2

Views: 2000

Answers (2)

Jens Erat
Jens Erat

Reputation: 38672

There only is one parent element. You're probably looking for ancestors:

//div[contains(text(),'div_text')]/ancestor::*

The query which is not working has a syntax error, you're applying a predicate on an imcomplete axies step (.../[name(parent::*)..., the node or a * is missing).

Upvotes: 0

Yi Zeng
Yi Zeng

Reputation: 32855

If I understood your question correctly, what you want is ancestor not parent.

XPath Axes

ancestor: Selects all ancestors (parent, grandparent, etc.) of the current node parent
parent: Selects the parent of the current node

Try //div[text()='title']/ancestor::table for table ancestors

Upvotes: 3

Related Questions