anubis
anubis

Reputation: 1505

How select a parent node with XPath?

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?

Upvotes: 3

Views: 16937

Answers (2)

kjhughes
kjhughes

Reputation: 111541

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.

Upvotes: 3

supputuri
supputuri

Reputation: 14135

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.

Upvotes: 9

Related Questions