2

I struggle currently to find the correct xpath expression to select an input element where its parent/sibling element contains a specific text.

In the example below, I would like to select the "input" element where, in the same tr row, a td element with a specific text exists.

my example path - returns no match

//input[contains(../../../td/text(),"15-935-331")]

source code

<tr>
    <td><a href="xxx" target="_blank">xxxx, yyyyy</a></td>
    <td>Mr</td>
    <td></td>
    <td> 15-935-331</td>
    <form id="betreuerModel" action="xxxx" method="POST">
      <td class="tRight">
        <input value="Bearbeiten" id="bearbeiten" name="bearbeiten" class="submit" title="Bearbeiten" type="submit"/>
      </td>
    </form>
</tr>
<tr>
 // .. next row with same structure
</tr>

2 Answers 2

5

The contains function, when given a nodeset, will only operate on the very first node in that nodeset. In your case, it is <td><a href="xxx" target="_blank">xxxx, yyyyy</a></td>. You could instead refactor your expression so that the predicate operates on all the nodes to check, and the contains function operates on a single item:

//input[../../../td/text()[contains(., "15-935-331")]]

This will get any input element, where the parent's parent's parent contains a td element with a text node containing the text 15-935-331.


A perhaps easier way to specify this would be to use ancestor::tr[1]/td in place of ../../../td.

//input[ancestor::tr[1]/td/text()[contains(.,"15-935-331")]]

This would get the first tr in the ancestor hierarchy, and operate on that.

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

Comments

3

As an alternative to the solution posted by Keith, you can use the following XPath expression:

//tr[td[contains(., "15-935-331")]]/form//input

This makes it a bit more independent of the actual structure of the HTML. It selects the tr which contains a td containing the given text, and from that tr it takes the input element anywhere below the form element.

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.