3

If I have

<div>
  <a>
    <table>
      <tr>
        <td value="val">

If I want to select the a containing a td with value="val", how can I do that?

I have tested:

//td[@value="val"]

But I obtain the td node, I want to obtain the a node. How can I achieve that with XPath?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
anubis
  • 1,425
  • 5
  • 18
  • 47
  • Possible duplicate of [XPath: Get parent node from child node](https://stackoverflow.com/questions/28237694/xpath-get-parent-node-from-child-node) – Heretic Monkey Sep 23 '19 at 13:22

2 Answers2

7

You can use either of the below options.

//td[@value="val"]/ancestor::a
^
td with value val
                   ^
                    ancestor link

or

Preferred xpath in this case

//a[.//td[@value="val"]]
^
Get me any link which have td with value as val.

or

The below xpath works now, but when there any change to the page eg: if table is moved into a div, then this xpath will break.

//td[@value="val"]/parent::tr/parent::table/parent::a

Personally I prefer the 2nd option atleast in this case as a does not have any specific properties. And ancestor::a will select any link which is ancestor of the td.

supputuri
  • 13,644
  • 2
  • 21
  • 39
3

The direct answer to your question about how to select a parent in XPath is to use the parent:: axis or the .. abbreviation. However, often, as in your case, you can select the targeted "parent" directly via a predicate on a descendant rather than selecting the descendant and then having to traverse back up to the parent. For example, ...

This XPath,

//a[.//td/@value = "val"]

will select all a elements with a td descendant with a @value attribute value equal to "val".


Update: I wasn't paying attention and now see that @suppurtui already provided the above XPath as an option. I'll leave this up for any benefit provided by my explanation, but please upvote @supputuri's answer (as I have just done). Thanks.

kjhughes
  • 106,133
  • 27
  • 181
  • 240