nologo
nologo

Reputation: 6308

xpath nearest element to a given element

I am having trouble returning an element using xpath. I need to get the text from the 2nd TD from a large table.

<tr> 
 <td> 
  <label for="PropertyA">Some text here </label>
 </td>
 <td> TEXT!! </td>
</tr>

I'm able to find the label element, but then I'm having trouble selecting the sibling TD to return the text.

This is how I select the label:

"//label[@for='PropertyA']"

thanks

Upvotes: 9

Views: 21321

Answers (3)

Illidan
Illidan

Reputation: 4237

Getting ANY following element:

//td[label[@for='PropertyA']]/following-sibling::*

Upvotes: 1

Gaim
Gaim

Reputation: 6844

You are looking for the axes following-sibling. It searches in the siblings in the same parent - there it is tr. If the tds aren't in the same tr then they aren't found. If you want to it then you can use axes following.

//td[label[@for='PropertyA']]/following-sibling::td[1]

Upvotes: 20

user357812
user357812

Reputation:

From the label element, it should be:

//label[@for='PropertyA']/following::td[1]

And then use the DOM method from the hosting language to get the string value.

Or select the text node (something I do not recommend) with:

//label[@for='PropertyA']/following::td[1]/text()

Or if there's going to be just this one only node, then you could use the string() function:

string(//label[@for='PropertyA']/following::td[1])

You can also select from the common ancestor tr like:

//tr[td/label/@for='PropertyA']/td[2]

Upvotes: 8

Related Questions