Reputation: 4514
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?
Upvotes: 1
Views: 373
Reputation: 89325
This is one possible way :
//td[
position() = count(//th[contains(.,'Col2')]/preceding-sibling::th)+1
]
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.
Upvotes: 4