1

I want to select one html element based upon the position of another using xpath. For example:

<table>
    <tr>
        <th>
            Col1
        </th>
        <th>
            Col2
        </th>
        <th>
            Col3
        </th>
        <th>
            Col4
        </th>
    </tr>
    <tr>
        <td>
            Value1
        </td>
        <td>
            Value2
        </td>
        <td>
            Value3
        </td>
        <td>
            Value4
        </td>
    </tr>
</table>

In this example I want the td which is in the same position in the collection of tds that the th with the contents Col2 is.

I can find the position of the th

//th[contains(.,'Col2')]

I want to avoid doing this

//td[2]

Is there any way I can link the two?

1 Answer 1

4

This is one possible way :

//td[
    position() = count(//th[contains(.,'Col2')]/preceding-sibling::th)+1
 ]

xpathtester demo

The XPath returns td at position equals to position of the th. position of the th is calculated by counting number of preceding sibling th, +1 since XPath position index starts from 1.

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

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.