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?

1

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.